Getters and Setters on angular.extend $scope
Getters and Setters on angular.extend $scope
我正在阅读一篇有趣的文章AngularJS:Tricks with angular.extend(),并解释了如何使用getters
和setters
与extend
。但有些观点我不明白。
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;
}
});
}]);
目录:
<body ng-controller="ThingController">
{{ things }} // one, two
</body>
我的问题:
¿为什么
get thingOne()
不返回oneeeeeee
?(get thingTwo()
也一样)¿哪里叫
set thingOne
和set thingTwo
?因为我从来没有在控制台上看到set thing 1
或set thing 2
.
¿如何在
angular.extend methods
内声明set method
? ¿是否可以从视图中断言值?
试试这个方式:
angular.extend($scope, {
get things() {
return $scope.thingOne + ' ' + $scope.thingTwo;
}
});
在这种情况下,将调用 Setter:
$scope.thingOne = 'test';
它与 angular.extend 无关 - 这些是属性访问器:getter 和 setter...允许您在对象字段的读/写中添加一些逻辑。
以下是您定义一个的方法:
var instance = {
get prop() { return this._prop },
set prop(value) { this._prop = value }
}
像这样使用它:
instance.prop = "new value"
var x = instance.prop
angular.extend
仅将此定义复制到$scope。您也可以使用Object.define
。如图所示:http://jsfiddle.net/v1bxyrx1/2/
相关文章:
- AngularJS:ng之后,重复$scope值未按预期更新
- $ionicplatform内的$scope不;不起作用
- 使用$scope方法时的ControllerAs语法
- 如何将ngrepeat下的ngmodel绑定到$scope
- 另一个if(!$scope.$$phase)$scope$apply()szenario-需要帮助才能通关
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- $scope变量被视为字符串AngularJs
- ng在更新$scope后重复不更新信息
- 如何覆盖主干中的extend方法
- 正在获取Angular以检测$scope中的更改
- 如何惯用地手动销毁scope&在AngularJS中重新创建
- Understanding Javascript scope with "var that = this&qu
- AngularJS,angular.element($0).scope()揭示了每个控制器的函数
- Ng出口无法访问父$scope
- ng选项-用vm替换$scope
- $scope变量,ng隐藏/显示
- 如何在使用Ractive.extend()时引用DOM元素
- 强制 $scope.$watch 只开火一次
- 对 angular.extend 的调用不会导致 $scope.$watch proc
- Getters and Setters on angular.extend $scope