logo
logo
AI Products 
Leaderboard Community🔥 Earn points

Know more about angular.extend in Angualrjs framework

avatar
siva cynixit
collect
0
collect
0
collect
4
Know more about angular.extend in Angualrjs framework

Extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.extend({}, object1, object2).

AngularJS has this built-in method for doing object to object copies called angular.extend(). It is a very powerful function that has many uses.

Let’s consider a mythical ThingController that looks like this using traditional AngularJS code:

app.controller(‘ThingController’, [ ‘$scope’, function($scope) {
$scope.thingOne = ‘one’;
$scope.thingTwo = ‘two’;
$scope.getThings = function() {
return $scope.thingOne + ‘ ‘ + $scope.thingTwo;
};
}]);

for more in-depth knowledge on Angularjs, enroll for live demo on angularjs course

Lots of assignment to $scope to create member variables (models) and methods. This is how it would look if we used angular.extend():

app.controller(‘ThingController’, [ ‘$scope’, function($scope) {
angular.extend($scope, {
thingOne: ‘one’,
thingTwo: ‘two’,
getThings: function() {
return $scope.thingOne + ‘ ‘ + $scope.thingTwo;
}
});
}]);

Using angular.extend() seems like a cleaner way to express all these assignments to $scope. The only nit I have with this is that models and methods are mixed in some arbitrary order. We could clean it up with code looking something like this:

app.controller(‘ThingController’, [ ‘$scope’, function($scope) {
// models
angular.extend($scope, {
thingOne: ‘one’,
thingTwo: ‘two’
});

// methods
angular.extend($scope, {
// in HTML template, something like {{ getThings() }}
getThings: function() {
return $scope.thingOne + ‘ ‘ + $scope.thingTwo;
}
});
}]);

 

collect
0
collect
0
collect
4
avatar
siva cynixit