簡體   English   中英

Angularjs指令的模板更新,但鏈接沒有

[英]Angularjs directive's template updates, but link does not

我有一個帶有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();
})

任何想法?

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

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

參見以下鏈接以獲取更多信息: https : //thinkster.io/a-better-way-to-learn-angularjs/scope-vs-scope

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM