ng-repeat始终呈现为指令模板中的最后一个

ng-repeat always rendering as last in directive template

本文关键字:最后一个 指令 ng-repeat      更新时间:2023-09-26

我有一个指令(<my-directive>)和子指令(<my-child-directive>),结构如下:

<my-directive>
        <my-child-directive caption="{{student}}" ng-repeat="student in students"></my-child-directive>
        <my-child-directive caption="static content1"></my-child-directive>  
</my-directive>

使用 ng-repeat 重复的第一个子指令和最后一个子指令是静态项。

现在我这里有两个问题:

问题1:在最终输出中,最后一个指令呈现为第一个<li>。有没有办法按照与子指令相同的顺序呈现<li>s

问题2:我在<my-directive>的模板中使用了一个隐藏的div来渲染临时目的的隐含。有没有办法避免这个不需要的div?

这是我的 Java 脚本代码:

app=angular.module('myApp', [])
app.controller("MyController",function($scope){
    $scope.students=["Alex","George","Phillip"];
});

app.directive('myDirective',function(){
    return{
        restrict:'E',
        transclude:true,
        template:"<ul><li ng-repeat='item in items'>{{item.caption}}</li></ul> <div ng-transclude ng-hide='true'></div>",
        controller:function($scope){
            $scope.items=[];
            this.addItem=function(subScope){ 
                 $scope.items.push(subScope);   
            }
        },
        link:function(scope,element,attrs){ 
        }
    };
});
app.directive('myChildDirective',function () {
    return {
        restrict: 'E',
        require:"^myDirective",
        scope:{
            caption:"@"
        },
        link:function(scope,element,attrs,parentCtrl){
            parentCtrl.addItem(scope);
        }
    }
})

小提琴:http://jsfiddle.net/fyds082s/5/

有人可以帮忙吗?

第二个指令的链接函数在他前面的指令之前执行。当您在执行静态指令时检查 ng-repeat 状态时,它显示索引为 0。它还没有完成编译ng-repeat。

我的猜测是,角度链接同级元素从最后一个到第一个,就像它首先从子元素链接一样

更新:

我的猜测是错误的。 所以我的新猜测它与子范围有关。例如,当将ng-if添加到第二个指令时,它确实是第二个执行的:http://jsfiddle.net/fyds082s/7/

<my-directive>
        <my-child-directive caption="{{student}}" ng-repeat="student in students"></my-child-directive>
        <my-child-directive caption="static content1" ng-if="true"></my-child-directive>  
</my-directive>

你认为下面的顺序是什么?

<my-directive>
  <my-child-directive caption="one" ng-if="true"></my-child-directive>
  <my-child-directive caption="two"></my-child-directive>
</my-directive>

如果你回答two, one那么就向你致敬。

这个有点不直观的结果背后的原因是像 ng-ifng-repeat 这样的"条件渲染"指令。它们都包含其宿主元素,但稍后呈现它 - 分别在$scope.$watch$scope.$watchCollection触发事件时 - 此时调用 myChildDirectivelink 函数。

最好的方法是不要依赖调用link函数的顺序来确定呈现顺序。