加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS:使用动态属性值的自定义指令在“ng-repeat”内不起作

发布时间:2020-12-17 08:07:29 所属栏目:安全 来源:网络整理
导读:你能解释为什么以下指令不起作用? attrs.ngMindirective似乎在链接函数内未定义。 Live example here HTML: body ng-controller="MyCtrl" ul li ng-repeat="person in people" {{ person.name }} span ng-mydirective="{{ person.age }}"/span /li /ul/bod
你能解释为什么以下指令不起作用?

attrs.ngMindirective似乎在链接函数内未定义。

Live example here

HTML:

<body ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="person in people">
      {{ person.name }}
      <span ng-mydirective="{{ person.age }}"></span>  
    </li>
  </ul>
</body>

JS:

var app = angular.module('myApp',[]);

app.directive('ngMydirective',function() {
  return {
    replace: true,link: function(scope,element,attrs) {
      if (parseInt(attrs.ngMydirective,10) < 18) {
        element.html('child'); 
      }
    }
  };
});

app.controller('MyCtrl',function($scope) {
  $scope.people = [
    {name: 'John',age: 33},{name: 'Michelle',age: 5}
  ];
});
您应该使用attrs。$观察具有实际价值。

另一种方法是将此值传递给指令的范围,并将其视为监视。

这两种方法都显示在这里(live example):

var app = angular.module('myApp',attrs) {
      attrs.$observe('ngMydirective',function(value) {
        if (parseInt(value,10) < 18) {
          element.html('child'); 
        }
      });
    }
  };
});
app.directive('ngMydirective2',scope: { ngMydirective2: '@' },attrs) {
      scope.$watch('ngMydirective2',function(value) {
        console.log(value);
        if (parseInt(value,10) < 18) {
          element.html('child'); 
        }
      });
    }
  };
});

app.controller('MyCtrl',age: 5}
  ];
});
<body ng-controller="MyCtrl">

  <ul>
    <li ng-repeat="person in people">
      {{ person.name }}
      <span ng-mydirective="{{ person.age }}"></span>  
    </li>
    <li ng-repeat="person in people">
      {{ person.name }}
      <span ng-mydirective2="{{ person.age }}"></span>  
    </li>
  </ul>

</body>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读