I stumbled upon an interesting article AngularJS: Tricks with angular.extend(), which delves into the usage of `getters` and `setters` in conjunction with `extend`. However, there are certain aspects that leave me puzzled.
Js:
app.controller('ThingController', [ '$scope', function($scope) {
// private
var _thingOne = 'one',
_thingTwo = 'two';
// models
angular.extend($scope, {
get thingOne() {
console.log("get thing1");
return _thingOne + 'eeeeee';
},
set thingOne(value) {
console.log("set thing 1");
if (value !== 'one' && value !== 'two'){
throw new Error('Invalid value ('+value+') for thingOne');
}
},
get thingTwo() {
console.log("get thing2");
return _thingTwo + 'oooooo';
},
set thingTwo(value) {
console.log("set thing 2");
if (value !== 'two' && value !== 'three'){
throw new Error('Invalid value ('+value+') for thingTwo');
}
}
});
// methods
angular.extend($scope, {
get things() {
return _thingOne + ' ' + _thingTwo;
}
});
}]);
Html:
<body ng-controller="ThingController">
{{ things }} // one, two
</body>
My queries:
Why isn't
oneeeeeee
returned fromget thingOne()
? What aboutget thingTwo()
?Where exactly is
set thingOne
called, and the same forset thingTwo
? I couldn't find any output likeset thing 1
orset thing 2
in the console.How can I define a
set method
within theangular.extend methods
? Is it feasible to assign a value from the view?