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

标签 javascript angularjs angularjs-directive

我有一个具有 2 种数据绑定(bind)范围的指令,如下所示:

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);
    }
  }
});

在我的路由中的 Template 中(使用 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();
})

有什么想法吗?

最佳答案

link 函数只运行一次,如果要处理它的新值,可以使用scope.$watch 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

关于javascript - Angularjs 指令的模板更新,但链接没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44135584/

相关文章:

javascript - 嵌套/共享 Angular 应用程序

angularjs - 删除所有芯片后不显示自动完成建议(md-chips + md-autocomplete)

html - 使用 ng-src 时如何在 Angular 指令中访问 src 属性

javascript - AngularJS - 跨 Controller 广播

javascript - 如何对路由发出 get 请求并从 API 检索信息?

Angularjs 和 Web 服务问题

javascript - Angular.js 指令与加载数据的两种方式绑定(bind)

angularjs - 后备图像的 Angular 指令

javascript - 从 Node fs 模块中的绝对路径读取本地文件

javascript - 使用服务器路由 react 路由器浏览器历史记录