自定义指令会杀死ngRepeat

时间:2014-04-10 20:05:39

标签: angularjs angularjs-ng-repeat

我担心我无法复制但是,唉,我可以复制失败:jsfiddle

这个例子很简单,但正是我所经历的。

基本上我有一个不使用模板的指令,它是通过$compile(element.contents())(scope)手动编译的。

该指令的目的是创建一个具有独特方法和帮助程序的隔离范围,以便在各个地方的整个应用程序中重用。


我有一个对象数组,我想用ngRepeat循环,但是我无法让这些项循环。

app.directive('myDir', function($compile){
    return {
        restrict: 'EA',
        scope: {
            migrate: '='
        },
        compile: function(tElement, tAttrs, transclude){

            return function Link(scope, element, attrs){
                scope.testArray = [{name: "1st item"}, {name: "2nd Item"}];
                // even tho it isn't printed, it's still in the scope.
                $compile(element.contents())(scope)
                // so is it just not being bound?
            }

        }
    }
})

1 个答案:

答案 0 :(得分:0)

跟踪代码时,ng-repeat的范围仍设置为运行时第一个控制器的范围。所以,当你告诉它重复“testArray”时,它不知道那是什么,因为它没有在第一个控制器的范围内定义。

你可以在这个小提琴中看到它确实可以访问第一个范围,但不能访问你的指令范围:http://jsfiddle.net/6Ndmp/

<强> HTML

<div ng-controller="MainCtrl">
    <h1>{{ title }}</h1>
    <p>ngRepeat doesn't seem to work...</p>
    <hr>
    <!-- I'm trying to create an isolate scope by passing starting data to the directive.
    This data would then be used to build out directive specific methods and getters... -->    
    <div my-dir migrate="send_to_directive">
        <p>I can print it: <code>{{ testArray | json }}</code></p>
        <p>But looping over it doesn't work...</p>
        <ul>
            <li><strong>Before Loop</strong></li>
            <li ng-repeat="item in send_to_directive">{{ item }}</li>
            <li><strong>After Loop</strong></li>
        </ul>
    </div>
    <!-- Unfortunatly, even tho the data is in the directive I cant seem to return it to the element... -->
</div>

那么为什么ng-repeat指令在你的指令之前链接?我不知道,但如果有其他人这样做,我很乐意学习。

相关问题