你如何在指令/模板中使用ng-repeat?

时间:2017-02-27 08:31:26

标签: angularjs angularjs-directive angularjs-ng-repeat

我正在尝试使用ng-repeat来迭代我定义的数组。这将写出一个自定义元素,它有一个指令/模板来替换它的HTML。

当我不使用ng-repeat时,自定义属性会在模板中被选中并填写,例如

<my-custom-elm customAttr1="customVal1" customAttr2="customVal2"></my-custom-elm>
<my-custom-elm customAttr1="customVal3" customAttr2="customVal4"></my-custom-elm>

app.directive('myCustomElm', function(){
    return {
        restrict: 'E',
        replace: true,
        scope: {
            customAttr1: '@',
            customAttr2: '@'
        },
        template: '<div class="{{ customAttr1 }}">{{ customAttr2 }}</div>'
    }
});

会写出:

<div class="customVal1">customVal2</div>
<div class="customVal3">customVal4</div>

然而,当我尝试使用ng-repeat迭代地执行此操作时,如下所示:

<my-custom-elm ng-repeat="x in jsArr" customAttr1="{{ x.customAttr1 }}" customAttr2="{{ x.customAttr2 }}"></my-custom-elm>

占位符没有收到任何价值。 HTML属性被写入元素,因此出于某种原因,它只是我引用不好的占位符。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您还需要将camel case转换为dash delimit for attribute customAttr1&gt; custom-attr1

&#13;
&#13;
angular.module('test', [])
  .controller('Test', Test)
  .directive('myCustomElm', myCustomElm);
  
function Test($scope) {
  $scope.jsArr = [
    {customAttr1: 'foo', customAttr2: 'bar'},
    {customAttr1: 'oof', customAttr2: 'rab'}
  ]
}

function myCustomElm() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      customAttr1: '@',
      customAttr2: '@'
    },
    template: '<div class="{{ customAttr1 }}">{{ customAttr2 }}</div>'
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<div ng-app='test' ng-controller='Test'>
  <my-custom-elm ng-repeat="x in jsArr" custom-attr1="{{ x.customAttr1 }}" custom-attr2="{{ x.customAttr2 }}"></my-custom-elm>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

尝试使用&#34; =&#39;而不是&#34; @&#34;内部范围:{}。