javascript - AngularJS : Directive not picking up attribute

标签 javascript angularjs angularjs-directive directive

我有以下指令:

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 控制台:

enter image description here

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

谢谢

最佳答案

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

使用一次性监视 - 您还可以考虑使用双向绑定(bind)隔离作用域指令

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

并将其绑定(bind)为:

   <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>

绑定(bind) promise /数据

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

并将其绑定(bind)为

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

事件总线

只需使用 Angular 事件总线并从 Controller 广播一个事件,该事件设置数据如char_loaded,使用scope.$on监听指令中的事件,一旦获得它就初始化。

关于javascript - AngularJS : Directive not picking up attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28080085/

相关文章:

javascript - 页面加载到另一个页面的 ID 时滚动到顶部失败

javascript - React JS 映射对象名称的问题

javascript - 如何列出元素,包括值(value)、名称、面额?

javascript - 我如何将 Wordpress API 与 ReactJs 混合使用

angularjs - 带有 Angular Form 的 Angular 对话框

javascript - 在 Angular 中滑动多级菜单和面包屑

javascript - 如何用 html 标签包装给定字符串的所有匹配并将其附加到指令的模板中

javascript - 似乎无法为选择选项设置默认选项;使用 Angular

angularjs - Angular ng-if 或 ng-show 响应缓慢(2秒延迟?)

javascript - AngularJS:数据传输不起作用?