[英]angular directive listen to prop change not acts
我创建了一个渲染d3的指令,该指令从props获取他的数据,如下所示:
<my-directive words="fromControllerData"></my-directive>
现在,“ fromControllerData”可以由父级更改,我想重新渲染指令。
如何收听数据更改?
发现了很多例子,但没有一个...
这是项目的链接: https : //plnkr.co/edit/I6eyFMBrhoDpxfOsulrI?p=preview
您会看到以下指令:
app.js // line 48
我尝试了scope。$ watch和scope。$ watchCollection ...
一些代码来解释:
推论者:
app.controller('AppController', ['$scope', '$rootScope', 'serverData', function($scope, $rootScope, serverData) {
$scope.data = {
words: serverData
};
setTimeout(function() {
console.log('changegd');
$scope.data.words = [];
}, 1000);
}]);
一些指令代码:
app.directive("gravityWordCloud", ['serverData', function(serverData) {
return {
restrict: "EA",
scope: {
words: "="
},
link: function(scope, element, attrs) {
// dontcare stuff
//this happens only on first load......
//but never again
scope.$watchCollection('words', function() {
console.log(scope.words);
});
}
}
}])
用这个:
scope.$watch('scope.words', function() {
console.log(scope.words);
}, true);
$ watch函数仅比较对象的引用,不会改变。 添加最后一个“ true”参数使其成为“深度”监视。 Angular文档中的函数签名( https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope):
$watch(watchExpression, listener, [objectEquality]);
另一种方法是创建一个返回单词的函数,并观察该函数:
scope.$watch(function() {
return someFunctionThatReturnsWords();
}, function() {
console.log(scope.words);
});
编辑:您还观看了“单词”而不是“ scope.words”
我已将以下代码添加到您的Plunker中,并且可以正常工作:
var getWords = function() {
return scope.words;
}
scope.$watch(getWords, function() {
console.log(scope.words);
}, true);
好吧,无论谁收到此错误,这都是最小的事情,但浪费大量时间...
我注意到“ words”变量在“超时”时也不会在控制器范围内更新,但是当我稍后用另一种方法手动更改它时,突然单击某些东西,我也会看到超时的变化。
底线:当我更改javascript时:
setTimeout
倾斜:
$timeout
突然之间一切正常...
所以可能是有范围和东西的东西...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.