获取递归ng-repeat中当前数组的长度

时间:2018-01-16 04:32:33

标签: javascript arrays angularjs angularjs-ng-repeat

看看这个小提琴 http://jsfiddle.net/uXbn6/4619/

这里我使用了递归模板来打印我的数据。 我想要的是'嗨'只有当井线长度大于1时,才能打印文本。

这里对于第一个阵列'树,因为长度大于1,应该打印Hi。现在在child中,当data.nodes重复循环时,data.nodes的长度为1或小于1,' Hi'不应该被打印出来。

总之,我希望这个例子的输出

  

firstParenNode你好       node1.1
      secondParenNode嗨

<script type="text/ng-template"  id="tree_item_renderer.html">
    <div> {{data.name}}
    <span ng-show="tree.length > 1"> Hi </span>
  </div>
    <div ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></div>

 </script>

<div ng-app="myApp" ng-controller="TreeController">
    <div ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></div>
</div>


angular.module("myApp", []).
controller("TreeController", ['$scope', function($scope) {
    $scope.tree = [{
        name: "firstParenNode", 
        nodes: [{
            name: "node1.1",
            nodes: []
        }]
    }, {
        name: "secondParenNode",
        nodes: []
    }];
}]);

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

试一试:

<script type="text/ng-template"  id="tree_item_renderer.html">
    <div> {{node.name}} 
        <span ng-show="node.nodes.length > 0"> Hi </span>
    </div>
    <div ng-repeat="node in node.nodes" ng-inlude="'tree_item_renderer.html'"></div>
</script>

<div ng-app="myApp" ng-controller="TreeController">
    <div ng-repeat="data in tree">
        <div> {{data.name}}
            <span ng-show="tree.length > 1"> Hi </span>
        </div>
        <div ng-repeat="node in data.nodes" ng-include="'tree_item_renderer.html'"></div>
    </div>
</div>

在我的小提琴上看到: http://jsfiddle.net/uXbn6/4622/

答案 1 :(得分:1)

如果我理解正确,只需替换

<span ng-show="tree.length > 1"> Hi </span>

<span ng-show="data.nodes.length > 1"> Hi </span>