This next group of functions can be executed from anywhere in Angular without having to inject them. They are mainly utility functions that allow you to do things easier or do things the Angular way.
This provides a way to combine two objects:
angular.extend(srcObject, destObject)
In JavaScript, there is no in-built way to extend an object using another object. This function does just that.
Here is a simple example that will extend one object with the other's property:
var first = { first: '1' }; var second = { second: '2' }; var extended = angular.extend(first, second); //extended will be {first:'1', second:'2'}
This is the no operation function:
angular.noop()
It is useful to have a function do no operation (noop
). A great example of this is when you have a function as a parameter that is optional. If it is not passed in, you can run noop
instead.
This is a simple example that demonstrates the scenario explained earlier:
function test(doSomething) { var callback = cb || angular.noop; callback('output'); }
This makes a copy of an object:
angular.copy(srcObject, [destObject])
This function returns the copy of srcObject
. If destObject
is supplied, it would be returned.
This binds a function to an object:
angular.bind(self, function, [args..])
This creates a new bound function that will execute in the context of self. This allows you to define a function and then execute it many times in different contexts. This is further extended by binding arguments as well.
This is a contrived example, but demonstrates the principles. First is a function that depends on the context to execute. It will add the first parameter to this
and multiply that result:
function addAndMultiply(toAdd, toMultiply) { return (this + toAdd) * toMultiply; }
Next, you will use angular.bind
to create a new function:
var newFunc = angular.bind(4, addAndMultiply, 1);
This can be executed, and the return value will be 5 times the multiplier. In newFunc
, this
is 4
, and toAdd
is 1
, so the inner parens will always be 5
. For example this will return 10
:
newFunc(2);
18.117.231.15