本文介绍了AngularJS:使用动态属性值的自定义指令在“ng-repeat"中不起作用;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could you explain please why the following directive doesn't work?

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

attrs.ngMydirective seems to be undefined inside the linking function.

此处为现场示例

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.$observe 来获得实际价值.

You should use attrs.$observe to have actual value.

另一种方法是将此值传递给指令的作用域并$watch 它.

Another approach is to pass this value to directive's scope and $watch it.

此处显示了两种方法(现场示例):

Both approaches are shown here (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>

这篇关于AngularJS:使用动态属性值的自定义指令在“ng-repeat"中不起作用;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 10:36