首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >AngularJS:使用动态属性值的自定义指令在"ng-repeat“中不起作用

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

Stack Overflow用户
提问于 2013-01-28 17:56:53
回答 1查看 20.6K关注 0票数 19

你能解释一下为什么下面的指令不起作用吗?

在链接函数中,attrs.ngMydirective似乎是undefined

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-28 18:15:32

你应该使用attrs.$observe来获得实际的值。

另一种方法是将该值传递给指令的作用域并对其执行$watch

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

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

app.directive('ngMydirective', function() {
  return {
    replace: true,
    link: function(scope, element, attrs) {
      attrs.$observe('ngMydirective', function(value) {
        if (parseInt(value, 10) < 18) {
          element.html('child'); 
        }
      });
    }
  };
});
app.directive('ngMydirective2', function() {
  return {
    replace: true,
    scope: { ngMydirective2: '@' },
    link: function(scope, element, attrs) {
      scope.$watch('ngMydirective2', function(value) {
        console.log(value);
        if (parseInt(value, 10) < 18) {
          element.html('child'); 
        }
      });
    }
  };
});

app.controller('MyCtrl', function($scope) {
  $scope.people = [
    {name: 'John', age: 33},
    {name: 'Michelle', 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>
票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14559475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档