Samantha J T Star
Samantha J T Star

Reputation: 32828

How can I watch to see when the number of items in an array changes in AngularJS?

I created this code:

    $scope.$watch('grid.view.length', function () {
        if ($scope.grid.view != null) {
            var a = $scope.grid.view.length;
            var pane = $('.scroll-pane').jScrollPane();
            pane.data('jsp').reinitialise();
        }
    })

grid.view is an array. All I need to do is see if the number of elements change but this seems not to trigger the watch when the number of elements inside of it changes. Am I doing this wrong ?

Maxim's comment sounds like a solution but I am not sure now. Would it better to just set up a $scope variable that holds the length and watch that. I am concerned if it does a lot of deep compares then this might be a performance problem. Note the grid.view is quite big.

Upvotes: 0

Views: 61

Answers (2)

AlwaysALearner
AlwaysALearner

Reputation: 43947

Your concern is reasonable. From the docs:

To save the value of the object for later comparison, the angular.copy function is used. It also means that watching complex options will have adverse memory and performance implications.

Using another scope variable that just holds the length is an overkill in your case.

$watch also accepts a function as a parameter. A change in the return value triggers a call to the listener:

$scope.$watch(function($scope){
    return grid.view.length;
},function(newValue, oldValue){
    /* do something */
    console.log("yeah! "+newValue);
});

Upvotes: 0

Maxim Shoustin
Maxim Shoustin

Reputation: 77910

Use flag true to make deep watch:

Try:

$scope.$watch('grid.view.length', function () {
        if ($scope.grid.view != null) {
            var a = $scope.grid.view.length;
            var pane = $('.scroll-pane').jScrollPane();
            pane.data('jsp').reinitialise();
        }
    }, true)

Upvotes: 1

Related Questions