$watch 不能处理来自其他控制器的变量? [英] $watch not working on variable from other controller?

查看:29
本文介绍了$watch 不能处理来自其他控制器的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它显示一个清单,并将选择存储在一个数组中.

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

我的另一个控制器在第一个控制器的数组上运行 $http.get.

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

如何设置 $watch 以便每当数组更改时,都会发送新的 HTTP GET 请求?

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

我的尝试: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'];

推荐答案

默认情况下,$watch 检查引用的更改,而不是相等.由于对象和数组在修改时仍然具有相同的引用,因此不会触发监视.至少有两个选项可以让它工作.

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) {
// ...

否则,您可以使用可选的 $watch 参数 objectEquality,它需要一个布尔值.这会进行相等性检查而不是引用检查.

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.

这篇关于$watch 不能处理来自其他控制器的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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