AngularJS:在指令链接函数中访问ng-repeat $ index以访问集合中的项目

时间:2014-07-27 08:08:07

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

我遇到了一堵墙,到目前为止,没有任何文件可以提供帮助。我正在尝试创建一个指令,用iframe替换一个指向外部资源的元素,并且我的数组中的每个项都有一个指向自己资源的链接。

我在控制器中的数据如下所示:

[
    {
        "title"     :   "Launch",
        "name"      :   "Barbaz",   
        "resource"  :   $sce.trustAsResourceUrl("http://external.domain:14168/Bar/Baz")
    },
    {
        "title"     :   "Launch",
        "name"      :   "Foobar",
        "resource"  :   $sce.trustAsResourceUrl("http://external.domain:14168/Foo/Bar")                                                 
    }
];

我的 html 如下所示:

<stuffs element="thing in things">
    <iframe ng-src="{{thing.resource}}" />
</stuffs>

我的指令如下所示:

stuffsModule.directive('stuffs', function ($parse){
    return {
        restrict: 'ACE',
        transclude: 'element',
        replace: true,
        scope: true,
        template: [
            '<ul>',
                '<li>',
                    '<iframe />',
                '</li>',
            '</ul>'
        ].join(''),

        compile: function (tElement, tAttrs, transclude) {
            var rpt = document.createAttribute('ng-repeat');
            rpt.value = tAttrs.element;
            tElement[0].children[0].attributes.setNamedItem(rpt);


            return function (scope, element, attr){ 
                var rhs = attr.element.split(' in ')[1];
                scope.facilities = $parse(rhs)(scope);
                var src = document.createAttribute('ng-src');
                src.value = scope.things[scope.$parent.$index].resource; //<= Blows Up

                element[0].children[0].children[0].attributes.setNamedItem(src);
            }
        }
    }
});

无论我做什么,范围。$ parent。$ index评估为 undefined

任何人都可以看到我在链接器函数中无法访问$ index的任何原因吗?我不应该通过编译中添加的ng-repeat指令为我连线吗?

1 个答案:

答案 0 :(得分:1)

不完全是您的问题的答案,但请看这里我希望这会对您有所帮助http://jsbin.com/tevuqe/1/edit

app.directive('stuffs', function ($parse){
    return {
        restrict: 'ACE',
        transclude: 'element',
        replace: true,
        scope: true,
        template: [
            '<ul>',
                '<li>',
                   '<p>{{thing.resource}}</p>',
                    '<iframe ng-src="{{thing.resource}}" />',
                '</li>',
            '</ul>'
        ].join(''),

        compile: function (tElement, tAttrs, transclude) {
            var rpt = document.createAttribute('ng-repeat');
            rpt.value = tAttrs.element;
          console.log(tAttrs.element);
            tElement[0].children[0].attributes.setNamedItem(rpt);



        }
    };
});
相关问题