【问题标题】:How do you use ng-repeat with a directive/template?您如何将 ng-repeat 与指令/模板一起使用?
【发布时间】:2017-02-27 19:23:04
【问题描述】:

我正在尝试使用 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 属性被写入元素,所以它只是占位符,由于某种原因,我引用得不好。

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    您还需要将驼峰大小写转换为属性的破折号分隔 customAttr1 > custom-attr1

    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>'
      }
    }
    <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>

    【讨论】:

      【解决方案2】:

      尝试在范围内使用“=”而不是“@”:{}。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-27
        • 2016-05-14
        • 1970-01-01
        • 2013-05-14
        • 1970-01-01
        相关资源
        最近更新 更多