Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watch not working on variable from other controller?

I have one controller which displays a checklist, and stores the selection in an array.

My other controller runs an $http.get on the array from the first controller.

How do I set a $watch so that whenever the array changes, a new HTTP GET request is sent?

My attempt: http://plnkr.co/edit/EaCbnKrBQdEe4Nhppdfa

// See plnkr for other controller + FooSelection factory + view
function SimpleQueryResCtrl($scope, $http, FooSelection) {
    $scope.foo_list_selection = FooSelection;

    $scope.$watch('foo_list_selection', function (newValue, oldValue) {
        if (newValue !== oldValue)
            $http.get('/api/' + $scope.foo_list_selection).success(function (largeLoad) {
                $scope.myData = largeLoad;
            });
    });
}

SimpleQueryResCtrl.$inject = ['$scope', '$http', 'FooSelection'];
like image 620
Foo Stack Avatar asked Jun 15 '26 05:06

Foo Stack


1 Answers

By default, a $watch checks for changes to a reference, not for equality. Since objects and arrays still have the same reference when modified, the watch is not triggered. There are at least two options to get it working.

If the only changes you want to be notified of modify the size of the array (adding or removing elements vs. changing the content of an element), you can set the watch on the length property of the array instead like:

$scope.$watch('foo_list_selection.length', function (newValue, oldValue) {
// ...

Otherwise, you can use the optional $watch argument objectEquality, which expects a boolean. This does an equality check rather than a reference check.

$scope.$watch('foo_list_selection', function (newValue, oldValue) {
    if (newValue !== oldValue)
        $http.get('/api/' + $scope.foo_list_selection).success(function (largeLoad) {
        $scope.myData = largeLoad;
    });
}, true);  // <- put `true` here

This is not the default behavior because it performs a more costly deep check of all the elements so only use when necessary.

like image 59
Dan Avatar answered Jun 17 '26 19:06

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!