19

您能否解释一下为什么以下指令不起作用?

attrs.ngMydirective似乎undefined在链接功能内。

现场示例在这里

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

1 回答 1

31

您应该使用attrs.$observe具有实际价值。

另一种方法是将此值传递给指令的范围和$watch它。

两种方法都在这里显示(现场示例):

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>
于 2013-01-28T10:15:32.217 回答