AngularJS:指令未拾取属性

AngularJS : Directive not picking up attribute

我得到了以下指令:

app.directive('ngAvatar', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<img class="avatar-medium" ng-src="{{url}}" />',
    link: function(scope, elem, attrs) {
      console.log(attrs);
      var aType = attrs.avatarType;
      var aId = attrs.avatarId;
      console.log("Type: "+ aType);
      console.log("Character ID:"+ aId);
      var baseUrl = "http://api-character.com/";
      switch(aType){
        case "character":
          scope.url = baseUrl + "Character/"+aId+"_256.jpg";
      }
    }
  }
});

不幸的是,该指令没有在指令中提取 avatar_id。如您所见,我正在控制台记录属性:

console.log("Type: "+ aType);
console.log("Character ID:"+ aId);

在我看来,我是这样使用这个指令的:

<ng-avatar avatar_type="character" avatar_id="{{character.character_id}}"></ng-avatar>

以下是我的控制台在Chrome中的输出。如您所见,avatar_id 显示为空白,但在检查 attrs 时,您可以看到该属性存在,但未显示在指令代码中。

Chrome 控制台:

有谁知道为什么它不起作用?

谢谢

解决这个问题的方法有很多种。

使用一次监视 - 你也可以考虑使用双向绑定隔离作用域指令

   link: function(scope, elem, attrs) { 
      //Set up watch
      var unWatch = scope.$watch(attrs.avatarId, function(v){
        if(v){
          unWatch();
          init();
        }
      });
     function init(){
       //initialize here
     }
   }

并将其绑定为:

   <ng-avatar avatar-type="character" avatar-id="character.character_id"></ng-avatar>

使用属性观察

  link: function(scope, elem, attrs) { 
      //Set up watch
      var unWatch = attrs.$observe(attrs.avatarId, function(v){
        if(v){
          unWatch();
          init();
        }
      });
     function init(){
       //initialize here
     }
  }

并与

一起使用
 <ng-avatar avatar-type="character" avatar-id="{{character.character_id}}"></ng-avatar>

绑定promise/data

  app.directive('ngAvatar', function($q) {
   //...
   link: function(scope, elem, attrs) { 
      //Set up watch
     $q.when(scope.$eval(attrs.character)).then(init); 

     function init(character){
       var id = character.id;
       //initialize here
     }
    }
  } 

并将其绑定为

 <ng-avatar avatar-type="character" avatar-id="characterPromiseOrCharObject"></ng-avatar>

事件总线

只需使用 angular 事件总线并从设置数据的控制器广播一个事件说 char_loaded,使用 scope.$on 在指令中监听事件,一旦你得到它初始化.