如何获取在angularjs更改的对象?对象、angularjs

2023-09-14 00:13:05 作者:他给旳回忆,多过伤

我用这个功能来观看对象的数组更改:

  $ $范围表(数据,功能(的newval){} /*...*/,真实); 

我怎样才能在哪个属性已经改变,这样我可以在一个阵列推对象?例如:

  VAR对myApp = angular.module(对myApp,[]);myApp.factory(数据,函数(){VAR数据= {[ID:1,属性:随机},{ID:2,属性:随机再次}];返回数据;});变种myBigArray = [];功能tableCtrl($范围,数据){    $ scope.TheData =数据;    $范围。$表(海图,函数(){    //这里的对象应该推    myBigArray.push(>>对象,其中财产已被更改<<<);    },真正的);} 

解决方案

修改:请注意,此解决方案原来是一个不好的做法,因为它是加入了很多观察家的,这是你不希望,因为它有一个性能损失。

=======

我最终想出了这个解决方案:

  items.query(功能(结果){    _(结果)。每个(函数(项目,我){        $ scope.items.push(项目);        $范围。$腕表('项目['+ I +']',函数(){            的console.log(项目); //这是改变的项目。        },真正的);    });}); 
在下一个Web应用程序中使用AngularJS的7大理由

I use this function to watch an array of objects for changes:

$scope.$watch('Data', function (newVal) { /*...*/ }, true);

How can I get an object in which property has been changed so that I can push it in an array? For example:

var myApp = angular.module("myApp", []);

myApp.factory("Data", function(){
var Data = [{id:1, property: "Random"}, {id:2, property: "Random again"}];
return Data;
});

var myBigArray = [];

function tableCtrl($scope, Data){
    $scope.TheData = Data;
    $scope.$watch("TheData", function() {

    //Here an object should be pushed
    myBigArray.push(">>Object in which property has been changed <<<");
    }, true);
}

解决方案

Edit: Note that this solution turns out to be a bad practice as it is adding a lot of watchers, which is something you do not want because it has a performance penalty.

=======

I eventually came up with this solution:

items.query(function (result) {
    _(result).each(function (item, i) {
        $scope.items.push(item);
        $scope.$watch('items[' + i + ']' , function(){
            console.log(item); // This is the item that changed.
        }, true);
    });
});