AngularJS:使用动态属性值的自定义指令不';“不要在里面工作”;ng repeat“;

AngularJS:使用动态属性值的自定义指令不';“不要在里面工作”;ng repeat“;,angularjs,angularjs-directive,Angularjs,Angularjs Directive,你能解释一下为什么下面的指令不起作用吗 attrs.ngMydirective似乎在链接函数中未定义 HTML: {{person.name} JS: var-app=angular.module('myApp',[]); app.directive('ngMydirective',function(){ 返回{ 替换:正确, 链接:函数(范围、元素、属性){ if(parseInt(attrs.ngMydirective,10)

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

attrs.ngMydirective
似乎在链接函数中未定义

HTML:


  • {{person.name}
JS:

var-app=angular.module('myApp',[]);
app.directive('ngMydirective',function(){
返回{
替换:正确,
链接:函数(范围、元素、属性){
if(parseInt(attrs.ngMydirective,10)<18){
html('child');
}
}
};
});
应用程序控制器('MyCtrl',函数($scope){
$scope.people=[
{姓名:约翰,年龄:33},
{姓名:'Michelle',年龄:5}
];
});

您应该使用
attrs.$observe
来获得实际值

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

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

var-app=angular.module('myApp',[]);
app.directive('ngMydirective',function(){
返回{
替换:正确,
链接:函数(范围、元素、属性){
属性$observe('ngMydirective',函数(值){
if(parseInt(值,10)<18){
html('child');
}
});
}
};
});
app.directive('ngMydirective2',function(){
返回{
替换:正确,
作用域:{ngMydirective2:'@'},
链接:函数(范围、元素、属性){
范围$watch('ngMydirective2',函数(值){
console.log(值);
if(parseInt(值,10)<18){
html('child');
}
});
}
};
});
应用程序控制器('MyCtrl',函数($scope){
$scope.people=[
{姓名:约翰,年龄:33},
{姓名:'Michelle',年龄:5}
];
});

  • {{person.name}
  • {{person.name}

对于任何看这里的人,我的问题是指令declaration中的大写字母。出于某种原因,将myDirective更改为myDirective使其工作。我使用的是dot net SP2013,并在ascx中使用大写字母,更改是在JS中
<body ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="person in people">
      {{ person.name }}
      <span ng-mydirective="{{ person.age }}"></span>  
    </li>
  </ul>
</body>
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}
  ];
});