[英]Angularjs directive's template updates, but link does not
I have a directive with 2 way data binding scope, as following: 我有一个带有2种方式的数据绑定范围的指令 ,如下所示:
app.directive('channelStar', function() {
return {
restrict: "E",
template: 'This works fine : {{count}}',
scope: {
count: '='
},
link: function(scope, element, attrs) {
// count is showing in template, but doesn't get updated here
// actually it logs old scopes value
console.log(scope.count);
}
}
});
In Template in my routing (using ui-router
and nested states) : 在我的路由模板中(使用
ui-router
和嵌套状态):
<channel-star count="selectedChannel[0].channel_dir_members"></channel-star>
Controller: 控制器:
httpService.request(...).then(function(result){
$scope.selectedChannel = result.data;
$rootScope.selectedChannel = result.data;
// $scope.$applyAsync();
// $rootScope.$applyAsync();
})
Any idea? 任何想法?
link
function only run once, if you want to deal with its new value, you can use scope.$watch
to watch count
. link
函数只能运行一次,如果要处理其新值,则可以使用scope.$watch
监视count
。
scope.$watch('count', function(newValue, oldValue) {
if(newValue){
//do something
}
}, true); // here parameter true is for deep compare objects, no need to use it when just for string
you can also use below code in your directive. 您还可以在指令中使用以下代码。 scope.$apply(function() {});
scope。$ apply(function(){});
see below link to for further information: https://thinkster.io/a-better-way-to-learn-angularjs/scope-vs-scope 参见以下链接以获取更多信息: https : //thinkster.io/a-better-way-to-learn-angularjs/scope-vs-scope
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.