Angularjs指令的模板更新,但链接没有

时间:2017-05-23 12:58:46

标签: javascript angularjs angularjs-directive

我有一个带<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);
    }
  }
});

在我的路由中使用模板(使用ui-router和嵌套状态):

<channel-star count="selectedChannel[0].channel_dir_members"></channel-star>

控制器:

httpService.request(...).then(function(result){
    $scope.selectedChannel = result.data;
    $rootScope.selectedChannel = result.data;
    // $scope.$applyAsync();
    // $rootScope.$applyAsync();
})

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

您也可以在指令中使用以下代码。 scope。$ apply(function(){});

请参阅以下链接以获取更多信息: https://thinkster.io/a-better-way-to-learn-angularjs/scope-vs-scope