$watch not working on variable from other controller?

前端 未结 3 496
鱼传尺愫
鱼传尺愫 2021-01-14 16:20

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 firs

3条回答
  •  耶瑟儿~
    2021-01-14 17:00

    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.

提交回复
热议问题