AngularJS: Custom directive using dynamic attribute value doesn't work inside “ng-repeat”

前端 未结 1 1517
余生分开走
余生分开走 2021-02-02 12:47

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

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

1条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 13:25

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

    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}
      ];
    });
    
    
    
      
    • {{ person.name }}
    • {{ person.name }}

    0 讨论(0)
提交回复
热议问题