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

时间:2015-02-27 15:39:33

标签: javascript angularjs angularjs-directive label

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

.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个输入,因此同一个指令的两个实例,并且这两个实例都会导致相同的标签可见。

这是一个小提琴http://jsfiddle.net/HB7LU/11330/

1 个答案:

答案 0 :(得分:3)

您需要使用指令的scope属性:

如果属性的名称相同:

    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">

参见章节&#39;隔离指令的范围&#39; 在AngularJS指令文档中:https://docs.angularjs.org/guide/directive