angular.extend
Blogs20152015-03-25
Angular extend()
According to angular document, angular.extend(dst, src) 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). More examples:
(function () {
"use strict";
var app = angular.module('myApp', []);
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;
}
});
}]);
// get, set?
app.controller(‘ThingController’, [‘$scope’, function ($scope) {
// private
var _thingOne = ‘one’,
_thingTwo = ‘two’;
// models
angular.extend($scope, {
get thingOne() {
return _thingOne;
},
set thingOne(value) {
if (value !== ‘one’ && value !== ‘two’) {
throw new Error(‘Invalid value(‘ + value + ‘) for thingOne’);
},
get thingTwo() {
return _thingTwo;
},
set thingTwo(value) {
if (value !== ‘two’ && value !== ‘three’) {
throw new Error(‘Invalid value(‘ + value + ‘) for thingTwo’);
}
});
// methods
angular.extend($scope, {
// in HTML template, something like {{ things }}
get things() {
return _thingOne + ' ' + _thingTwo;
}
});
}]);
}());
(function () {
"use strict";
angular.module('app.reader.models').factory('readerModel',
[function () {
return {
Reader: function createReaderModel(config) {
return angular.extend({
id: utilitiesService.generateID(),
age: null,
phone: null,
name: "",
address: null
}, config);
}
}
}]);
}());