【发布时间】:2014-12-20 14:24:33
【问题描述】:
在我的自定义指令中,我根据数据源数组中的对象数量向 DOM 添加元素。我需要观察每个对象中的特定属性。当我将这些元素添加到 DOM 时,我想在 toppings 数组中每个对象的 checked 属性上设置一个 $watch,但它不起作用,我不知道为什么。我在函数内部设置了一个断点,当属性从 true 变为 false 或 false 变为 true 时应该调用该断点,但该函数从未被调用。原因明显吗?我只是在学习 Angular,所以我很容易犯一个愚蠢的错误。
$scope.bits = 66; (i.e. onions and olives)
$scope.toppings = [
{ topping: 1, bits: 2, name: 'onions' },
{ topping: 2, bits: 4, name: 'mushrooms' },
{ topping: 3, bits: 8, name: 'peppers' },
{ topping: 4, bits: 16, name: 'anchovies' },
{ topping: 5, bits: 32, name: 'artichokes' },
{ topping: 6, bits: 64, name: 'olives' },
{ topping: 7, bits: 128, name: 'sausage' },
{ topping: 8, bits: 256, name: 'pepperoni' }
]
模型中的每个对象都有一个新的checked 属性,该属性为真或假。
注意:对象数组最多包含十几个项目。性能不是问题。
link: function link(scope, iElement, iAttrs, controller, transcludeFn) {
<snip>
// At this point scope.model refers to $scope.toppings. Confirmed.
angular.forEach(scope.model, function (value, key) {
// bitwise: set checked to true|false based on scope.bits and topping.bits
scope.model[key].checked = ((value.bits & scope.bits) > 0);
scope.$watch(scope.model[key].checked, function () {
var totlBits = 0;
for (var i = 0; i < scope.model.length; i++) {
if (scope.model[i].checked) totlBits += scope.model[i].bits;
}
scope.bits = totlBits;
});
});
<snip>
【问题讨论】:
标签: angularjs angularjs-directive watch