29

我基本上想要绑定到 Backbone 集合中的“添加”和“删除”事件。我认为在 AngularJS 中基本上没有办法做到这一点,而我们目前解决的解决方法是$watch()读取数组length并手动比较/重新计算整个事情。这真的是酷孩子所做的吗?

编辑:具体来说,观察数组的长度意味着我不容易知道哪个元素已更改,我需要手动“区分”。

4

5 回答 5

36

我认为 using$watch是一个很好的解决方案,但$watchCollection对你来说可能更好。$watchCollection不执行深度比较,只监视数组修改,如插入、删除或排序(不是项目更新)。

例如,如果要保持属性order与数组顺序同步:

$scope.sortableItems = [
    {order: 1, text: 'foo'},
    {order: 2, text: 'bar'},
    {order: 3, text: 'baz'}
];

$scope.$watchCollection('sortableItems', function(newCol, oldCol, scope) {
    for (var index in newCol) {
        var item = newCol[index];
        item.order = parseInt(index) + 1;
    }
});

但是对于你的问题,不知道有没有比手动浏览数组来识别变化更好的解决方案。

于 2014-04-08T10:46:56.987 回答
12

在 Angular 中观察数组的方法是 $watch(array, function(){} ,true)

于 2013-03-28T12:41:18.840 回答
3

我会创建子范围并单独观察它们。这是一个例子:

$scope.myCollection = [];
var addChild = function()
{
  var Child = $scope.$new();
  Child.name = 'Your Name here';

  Child.$watch('name', function(newValue) {
     // .... do something when the attribute 'name' is changed ...
  });

  Child.$on('$destroy', function() {
    //... do something when this child gets destroyed 
  });


  $scope.myCollection.push(Child); // add the child to collection array

};

// Pass the item to this method as parameter, 
// do it within an ngRepeat of the collection in your views 
$scope.deleteButtonClicked = function(item)
{
  var index = $scope.myCollection.indexOf(item); //gets the item index
  delete $scope.myCollection[index]; // removes the item on the array
  item.$destroy(); // destroys the original items
}
于 2013-12-08T08:35:22.660 回答
0

请详细说明您的用例。跟踪元素持久性的解决方案之一是使用带有自定义指令的 ngRepeat 指令来监听元素的 $destroy 事件:

<div ng-repeat="item in items" on-delete="doSomething(item)">

angular.module("app").directive("onDelete", function() {
    return {
        link: function (scope, element, attrs) {
            element.on("$destroy", function () {
                scope.$eval(attrs.onDelete);
            });
        }
    }
});
于 2013-03-28T13:04:24.870 回答
0

也许解决方案是创建集合类(就像主干一样),您也可以很容易地挂钩事件。

我在这里所做的解决方案并不是很全面,但应该给你一个关于如何做到这一点的一般指导。

http://beta.plnkr.co/edit/dGJFDhf9p5KJqeUfcTys?p=preview

于 2013-03-28T14:19:08.670 回答