【问题标题】:ng-repeat inside a directive template - access index指令模板内的 ng-repeat - 访问索引
【发布时间】:2015-12-09 22:40:01
【问题描述】:

我有以下问题:

我有一个自定义指令,它通过在模板字符串中使用 ng-repeat 来显示一个或多个表。在每个表中,放置了几个其他自定义指令。我希望这些知道所用元素的索引,但无法完成这项工作。我的代码现在看起来像这样:

.directive('myStuffText', function ($rootScope){
    return {
        restrict: 'A',
        require: '^form',
        replace: true,
        scope: true,
        template:
        ......
        '<table border="1" ng-repeat="elt in myModel.newStuffList">
        ......

        '<tr>' +
        '<td colspan="3"><div my-add-some-editor my-element-index="$index"/></td>' +
        '</tr>' 
        '</table>',

        link: function (scope, elt, attrs){
            scope.cockpitPolicyModel.newPolicyList = [];
        }
    };

})

独立于我的尝试,我总是在 my-add-some-editor 指令的模板函数中获取字符串 $index 或 {{$index}},而不是它的值..

编辑 - 添加嵌套指令:

.directive('myAddSomeEditor', function($rootScope){
    return {
        restrict: 'A',
        require: '^form',
        scope: true,

        template: function ($scope, $attr){


            return 
            .....
            '<span id="myAddSomeEditor" name="myAddSomeEditor" class="form-control" my-generic-editor '+
            'my-input-mapping="myModel.someText"></span>'
            .....
            ;
            }
    };
})

【问题讨论】:

  • 能否也添加嵌套指令my-add-some-editor
  • 试试$parent.$index
  • 一些建议 - 如果您提供像上面那样的内联模板,那么您应该使用 join ,因为它更好一点,但归结为个人喜好。模板:['
    ', '

    Hello World

    ', '
    '].join('') 另外 - 你应该在你的 ng-repeat 中使用track by $index,因为它是推荐的为了表现。 ng-repeat="elt in myModel.newStuffList track by $index"
  • 您的代码与您的问题无关。至少显示“那些”嵌套指令中的一个或“myStuffText”是其中之一怎么样?
  • 刚刚编辑了问题以添加嵌套指令

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


【解决方案1】:

这可能是因为在您的 my-add-some-editor 指令中,您在隔离范围内有此定义:

myElementIndex: '@'

这就是为什么你会得到你在 HTML 中写的文字字符串。

将其更改为:

myElementIndex: '='

编辑:既然您说您没有使用隔离范围,请在父指令中尝试:尝试执行 my-element-index="{{$index}}"。这在子指令的链接函数中:

link: function (scope, elem, attr) {
    attr.$observe('index', function(val) {
      scope.index = val;
    });
}

【讨论】:

  • 我尝试添加,但没有成功...我实际上并没有隔离范围
猜你喜欢
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多