获取在HTML标记中输入的指令值

时间:2016-11-03 22:42:45

标签: angularjs angularjs-directive

In this plunk我试图在指令中获取一个数组,其值在指令声明中的<li>列表中输入。

鉴于此指令声明:

<directive>
  <ul>
    <li id="0">xxx 0</li>        
    <li id="1">xxx 1</li>        
    <li id="2">xxx 2</li>        
  </ul>
</directive>

数组应返回如下内容:

scope.array = [ {id:0, name: "xxx 0"}, {id:1, name: "xxx 1"}, {id:2, name: "xxx 2"} ];

这是我的尝试(不起作用):

angular.module('app', []);

angular.module('app')
.directive('directive', function() {
    var directive = {};
    directive.restrict = 'AE';
    directive.template = "<div>{{array}}</div>";
    directive.scope = true;
    directive.link = function(scope, element, attrs) {
        scope.array = element.find("ul")[0].children;
    };
    return directive;

});

1 个答案:

答案 0 :(得分:1)

这是更新的plnkr http://plnkr.co/edit/QtNkOGvLMdu3w6BS3tlB?p=preview

您可以在模板中看到预期的数组。

必需的JS代码:

angular.module('app', []);

angular.module('app')
.directive('directive', function() {
    var directive = {};
    directive.restrict = 'AE';
    directive.scope = true;
    directive.link = function(scope, element, attrs) {
      var newArray = [];
      angular.forEach(element.find('ul')[0].children, function(val) {
        newArray.push({id: val.id, name: val.innerHTML});
      });
      scope.array = newArray;
    };
    directive.template = "<div><pre>{{array|json}}</pre><span ng-transclude></span></div>";
    directive.transclude = true;
    return directive;

});