The angular.extend()
function has very powerful to copy object to another object, including all of properties from the source object(s).
Usage
angular.extend(dst, src);
dst: destination object
src: source object(s)return: refercen to dst object
Example
Let’s understand how to use it with example instance. Create a normal controller which contains user’s name, gender and age. And create a method to get the full description of the user.
1 | angular.Module('app',[]) |
We can use angular.extend function to do like above functionality, see below:
1 | app.controller('UserController', ['$scope', function($scope) { |
And also we can use angular.extend() function to implement mixins. Let’s consider the below contrived Logging class.
1 | var debug = true; |
If we set debug variable to true, so it will print message in the browser console window when we invoke the log function. Otherwise nothing will be printed.
Okay, now we create a controler called LoggerController, and “mixin” Logger class to it.
1 | app.controller('LoggerController', ['$scope', function($scope) { |
In LoggerController, we “mixin” the Logger class to the $scope, and this will inovke the log function of the Logger class when the print function was called.