具有不同数据的 AngularJS 指令的多个实例?

Multiple Instances of AngularJS Directive with different data?

我有一个基本上为输入生成标签标签的指令。它用我的模板替换了指令,并确保父节点和下一个节点具有正确的属性和 类 我需要的。

.directive('placeHolder', function() {
    return {
    restrict: 'E',
    replace: true,
    template: '<label for="{{input}}" class="placeholder-label">{{label}}</label>',

    link: function ($scope, elem, attrs) {
      $scope.label = attrs.label;
      $scope.input = attrs.input;
      //check if the parent element is a div, then set the class to make it's position relative
      if(elem.parent().nodeName === 'DIV') {
        elem.parent().addClass('placeholder-parent');
      }

      //check if the next element is an input or textarea
      if(elem.next().nodeName === 'INPUT' || elem.next().nodeName === 'TEXTAREA') {
        //ensure the id of the input/textarea is the same as the for value in the label, else set it so
        if(elem.next().attr('id') === input) {
          return
        } else {
          elem.next().attr('id', input)
        }
      }
    }
  };

});

我的问题是我在同一页面上有 2 个输入,因此同一指令的两个实例,并且这两个实例导致相同的标签可见。

这里是fiddlehttp://jsfiddle.net/HB7LU/11330/

您需要使用指令的范围属性:

如果属性名称相同:

    scope: {
      label: '@',
      input: '@'
    }

或者您可以定义自定义的:

    scope: {
      myLabel: '=label',
      myInput: '=input'
    },

您的代码示例已修改:

app.directive('placeHolder', function() {
    return {
    restrict: 'E',
    replace: true,
    template: '<label for="{{input}}" class="placeholder-label">{{label}}</label>',
    scope: {
      label: '@',
      input: '@'
    },
    link: function ($scope, elem, attrs) {
      //check if the parent element is a div, then set the class to make it's position relative
      if(elem.parent().nodeName === 'DIV') {
        elem.parent().addClass('placeholder-parent');
      }

      //check if the next element is an input or textarea
      if(elem.next().nodeName === 'INPUT' || elem.next().nodeName === 'TEXTAREA') {
        //ensure the id of the input/textarea is the same as the for value in the label, else set it so
        if(elem.next().attr('id') === input) {
          return
        } else {
          elem.next().attr('id', input)
        }
      }
    }
  };

});

要使用它,请将您的指令 html 修改为:

<place-holder label="labelText" input="inputId">

参考章节'Isolating the Scope of a Directive' 在 AngularJS 指令文档中:https://docs.angularjs.org/guide/directive