$看不工作的其他控制器的变量? [英] $watch not working on variable from other controller?
问题描述
我有一个控制器,它显示一个清单,并在一个数组存储选择。
我的另外一个控制器上运行的 $ http.get
从第一个控制器的阵列上。
我如何设置一个 $观看
这样,每当阵列的变化,一个新的HTTP GET请求被发送?
我的尝试: http://plnkr.co/edit/EaCbnKrBQdEe4Nhppdfa
//看到其他控制器+ FooSelection工厂+视图plnkr
功能SimpleQueryResCtrl($范围,$ HTTP,FooSelection){
$ scope.foo_list_selection = FooSelection; $范围。$腕表('foo_list_selection',功能(为newValue,属性oldValue){
如果(为newValue!==属性oldValue)
$ http.get('/ API /'+ $ scope.foo_list_selection).success(功能(largeLoad){
$ scope.myData = largeLoad;
});
});
}。SimpleQueryResCtrl $注射='$范围,$ HTTP','FooSelection'];
默认情况下, $观看
检查变为一个参考,而不是平等。由于对象和数组修改时,仍具有相同的参考,手表不会被触发。至少有两个选项得到它的工作。
如果您希望收到的唯一的变化修改数组的大小(添加或删除元素对改变元素的含量),可以设置表上,而不是数组一样的长度属性:
$范围。$腕表('foo_list_selection.length',功能(为newValue,属性oldValue){
// ...
否则,您可以使用可选的 $观看
参数 objectEquality
,这需要一个布尔值。这确实相等性检查,而不是参考检查。
$范围。$腕表('foo_list_selection',功能(为newValue,属性oldValue){
如果(为newValue!==属性oldValue)
$ http.get('/ API /'+ $ scope.foo_list_selection).success(功能(largeLoad){
$ scope.myData = largeLoad;
});
},真正的); //< - 把`这里TRUE`
这是不是默认的行为,因为它执行的所有元素的更昂贵的深层检查,因此只能用在必要的时候。
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'];
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.
这篇关于$看不工作的其他控制器的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!