Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object that was changed in angularjs?

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);
}
like image 416
CoolCodeBro Avatar asked Apr 20 '13 17:04

CoolCodeBro


2 Answers

I don't see a way currently in Angular to get the changed object... I suspect you might need to traverse the new array and try to find the differences with the old array...

like image 58
Shai Reznik - HiRez.io Avatar answered Nov 10 '22 10:11

Shai Reznik - HiRez.io


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);
    });
});
like image 22
Bas Slagter Avatar answered Nov 10 '22 09:11

Bas Slagter