Angularjs $ watch tree array

时间:2014-09-18 10:53:07

标签: javascript angularjs angularjs-scope angularjs-ng-repeat

我有一个像这样的树形数组:

Array
(
    [attributes] => Array
        (
            [attribute_group_id_6] => Array
                (
                    [id] => 6
                    [name] => Processor
                    [items] => Array
                        (
                            [0] => Array
                                (
                                    [product_id] => 40
                                    [attr_id] => 1
                                    [attr_text] => demo
                                    [attr_group_id] => 6
                                    [attr_group_order] => 1
                                    [attr_group_name] => Processor
                                )

                            [1] => Array
                                (
                                    [product_id] => 28
                                    [attr_id] => 2
                                    [attr_text] => 10
                                    [attr_group_id] => 6
                                    [attr_group_order] => 5
                                    [attr_group_name] => Processor
                                )

                            [2] => Array
                                (
                                    [product_id] => 28
                                    [attr_id] => 3
                                    [attr_text] => 777
                                    [attr_group_id] => 6
                                    [attr_group_order] => 3
                                    [attr_group_name] => Processor
                                )

                        )

                )

        )
    )

目标是改变w items.[N].product_id

此代码可以看到更改但是,它会同时看到所有3个更改。

$scope.$watch('filterData.attributes.items', function(val, old) {
   console.log('watch');
}, true);

console:
watch
watch
watch

通过文本字段更改值:

questin是 - 如何只观看一次变化? (attributes.attribute_group_id_6.items.[N].product_id)

1 个答案:

答案 0 :(得分:0)

您的回调会触发整个items数组中的每次更改。你真正需要的是每个单独项目的监听器,你可以在一个循环中创建 - 虽然JSHint可能不喜欢这个。

for (var i = 0; i < $scope.filterData.attributes.items.length; i++) {
  $scope.$watch('filterData.attributes.items[' + i + ']', function(val, old) {
    console.log('watch');
  }, true);
}