使用select
绑定到控制器变量的a,只要变量在父控制器中存在并且在父$watch
变量中的该变量上创建a ,父触发器$watch
就不会触发。为什么会这样?
该代码并不重要,但为清楚起见而包含在内。
function populate(x) {
var items = [];
for (var i = 0; i < x; i++) {
items.push( { label: 'item ' + i,
data: { value: 'some value ' + i },
id: i });
}
return items;
};
function parent($scope) {
$scope.items = populate(10);
$scope.selected = $scope.items[0];
$scope.fired = 0;
$scope.$watch('selected.id', function(id) {
$scope.fired++;
});
};
function child($scope) {
};
此方案按说明工作。在这种情况下,$scope.fired
只要用户更改选择的值,变量就会增加。jsFiddle
<div ng-app>
<div ng-controller="parent">
<select ng-model="selected"
ng-options="item as item.label for item in items">
</select>
<pre>
{{ fired | json }}
</pre>
<pre>
{{ selected | json }}
</pre>
</div>
</div>
在下列情况下,$watch
将不会在父触发。但是,如果将$watch
移至子控制器,它将触发。注意:与上面的代码相比,更改在第3行。jsFiddle
<div ng-app>
<div ng-controller="parent">
<div ng-controller="child">
<select ng-model="selected"
ng-options="item as item.label for item in items">
</select>
<pre>
{{ fired | json }}
</pre>
<pre>
{{ selected | json }}
</pre>
</div>
</div>
</div>
为什么包含子控制器$watch
,即使子控制器继承了,也不会触发$scope
?
父母selected
没有改变自己。子范围selected
是。这就是为什么手表无法正常工作的原因。这是由于原型继承。
在$watch
本身应该在儿童范围进行定义,而与父范围是一个宣称它在首位的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句