link directives angularjs angularjs-directive

directives - AngularJS: la directiva personalizada que usa un valor de atributo dinámico no funciona dentro de "ng-repeat"



directive angularjs (1)

¿Podría explicar por qué la siguiente directiva no funciona?

attrs.ngMydirective parece estar undefined dentro de la función de enlace.

Ejemplo vivo aquí

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


Debe usar attrs.$observe para tener el valor real.

Otro enfoque es pasar este valor al alcance de la directiva y $watch .

Ambos enfoques se muestran aquí ( ejemplo en vivo ):

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>