gpt4 book ai didi

AngularJS : watching a particular property in an array of objects for changes in the property's value

转载 作者:行者123 更新时间:2023-12-04 15:22:08 27 4
gpt4 key购买 nike

在我的自定义指令中,我根据数据源数组中的对象数量向 DOM 添加元素。我需要观察每个对象中的特定属性。当我将这些元素添加到 DOM 时,我想在 checked 上设置一个 $watch toppings中每个对象的属性数组,但它不起作用,我不知道为什么。我在函数内部设置了一个断点,当属性从 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>

最佳答案

对象数组:

$scope.toppings = [
{ topping: 1, bits: 2, name: 'onions' },
{ topping: 2, bits: 4, name: 'mushrooms' },
{ topping: 3, bits: 8, name: 'peppers', checked:undefined /*may be*/ }
];
使用 AngularJs $WatchCollection 观看:
而不是监控 objects上面的数组,可以为对象中的任何属性更改,我们将创建一个我们正在观察其集合的元素的属性数组( .checked )。
我们 filter数组的元素只监视那些具有 .checked 的元素定义和 map到 Angular 数组 watchCollection .
当更改触发时,我将比较 ( .checked ) 的旧数组和新数组,以使用 lodash difference 获得精确更改的元素。方法。
 $scope.$watchCollection(

// Watch Function
() => (
$scope
.toppings
.filter(tp => tp.checked !== undefined)
.map(tp => tp.checked)
),

// Listener
(nv, ov) => {
// nothing changed
if(nv == ov || nv == "undefined") return;

// Use lodash library to get the changed obj
let changedTop = _.difference(nv,ov)[0];

// Here you go..
console.log("changed Topping", changedTop);
})

关于AngularJS : watching a particular property in an array of objects for changes in the property's value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26553150/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com