[英]How to watch change of variable from inside a directive?
I have a custom directive that is coded like this: 我有一个这样的自定义指令:
angular.module('client.core.directives')
.directive('containerlayout', function () {
function link(scope, el, attr) {
scope.$watch(['xdim', 'ydim', 'numOrder'], function () {
console.log("Watch Xdim/Ydim/numOrd change");
// do something when these changesd
}, true);
scope.$watch('labels', function (labels) {
// do something when labels array changes
}, true);
}
return {
link: link,
restrict: 'E',
scope: { geometry: '=geometry', xdim: '=xdim',
ydim: '=ydim', numOrder: '=numorder', labels: '=labels',
states: '=states', emptyToSkipped: '=emptytoskipped' }
};
and I have the following declaration: 我有以下声明:
<containerlayout geometry="rect" xdim="cont.xdim"
ydim="cont.ydim" numorder="1" labels="cont.labels"
states="cont.states" emptytoskipped="emptytoskipped"
class="ng-isolate-scope"></containerlayout>
but when I change,say the $scope.cont.xdim or some other variables, nothing happens and watches are not firing. 但是当我更改时,比如说$ scope.cont.xdim或其他一些变量,什么也没有发生,并且手表没有触发。
Note that xdim and ydim are integers and labels is array. 请注意,xdim和ydim是整数,标签是数组。
How I should I declare things in directive so it will watch the variables? 我应该如何在指令中声明东西,以便它可以监视变量? do they need to be initialized first thing in the controller for successfull work?
是否需要先在控制器中初始化它们才能成功工作? I need to remain in isolated scope if possible.
如果可能,我需要保持隔离状态。
$watch('propertyName', func)
watches for only one $scope.propertyName
. $watch('propertyName', func)
仅$scope.propertyName
一个$scope.propertyName
。
If you want to watch for several properties, you need $watchCollection('[propertyName, anotherPropertyName]', func)
. 如果要监视多个属性,则需要
$watchCollection('[propertyName, anotherPropertyName]', func)
。
scope.$watchCollection('[xdim, ydim, numOrder]', function (valuesArray) {
console.log("Watch Xdim/Ydim/numOrd change", valuesArray);
}, true);
Does labels
watcher trigger in your example? labels
观察者是否在您的示例中触发? It should, because it is only one property containing an array. 应该的,因为它只是一个包含数组的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.