如何获取在angularjs更改的对象? [英] How to get an object that was changed in angularjs?

查看:136
本文介绍了如何获取在angularjs更改的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  $ $范围表(数据,功能(的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(项目); //这是改变的项目。
        },真正的);
    });
});

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);
    });
});

这篇关于如何获取在angularjs更改的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆