我正在尝试显示元素的二叉树,我使用 ng-include 递归地遍历它。
ng-init="item = item.left"
和 ng-repeat="item in item.left"
有什么区别?
在此示例中,它的行为完全相同,但我在项目中使用了类似的代码,但它的行为却有所不同。我想这是因为 Angular 作用域。
也许我不应该使用 ng-if,请向我解释如何做得更好。
pane.html 是:
<div ng-if="!isArray(item.left)">
<div ng-repeat="item in [item.left]" ng-include="'Views/pane.html'">
</div>
</div>
<div ng-if="isArray(item.left)">
{{item.left[0]}}
</div>
<div ng-if="!isArray(item.right)">
<div ng-repeat="item in [item.right]" ng-include="'Views/pane.html'">
</div>
</div>
<div ng-if="isArray(item.right)">
{{item.right[0]}}
</div>
<div ng-if="!isArray(item.left)">
<div ng-init = "item = item.left" ng-include="'Views/pane.html'">
</div>
</div>
<div ng-if="isArray(item.left)">
{{item.left[0]}}
</div>
<div ng-if="!isArray(item.right)">
<div ng-init="item = item.right" ng-include="'Views/pane.html'">
</div>
</div>
<div ng-if="isArray(item.right)">
{{item.right[0]}}
</div>
Controller 是:
var app = angular.module('mycontrollers', []);
app.controller('MainCtrl', function ($scope) {
$scope.tree = {
left: {
left: ["leftleft"],
right: {
left: ["leftrightleft"],
right: ["leftrightright"]
}
},
right: {
left: ["rightleft"],
right: ["rightright"]
}
};
$scope.isArray = function (item) {
return Array.isArray(item);
}
});
编辑: 首先,我遇到了指令 ng-repeat 比 ng-if 具有更高优先级的问题。我试图将它们结合起来,但失败了。 IMO 奇怪的是 ng-repeat 支配 ng-if。
最佳答案
Pass parameter to Angular ng-include
你不需要那个。所有ng-include
的来源具有相同的 Controller 。因此每个 View 都会看到相同的数据。
What is the difference between ng-init="item = item.left" and ng-repeat="item in item.left"
[ 1 ]
ng-init="item = item.left"
意味着 - 创建名为 item 的新实例等于 item.left
.换句话说,您可以通过在 Controller 中编写来实现相同的目的:
$scope.item = $scope.item.left
[2]
ng-repeat="item in item.left"
表示基于 item.left
创建范围列表大批。你应该知道 ng-repeat
中的每一项有其私有(private)范围
I am trying to display a binary tree of elements, which I go through recursively with ng-include.
我在过去的回答中发布了如何使用 ng-include
显示树.
可能有帮助: how-do-display-a-collapsible-tree
此处的主要部分是您使用 id
创建节点由 <scipt>
包裹标记并使用 ng-repeat
:
<script type="text/ng-template" id="tree_item_renderer">
<ul class="some" ng-show="data.show">
<li ng-repeat="data in data.nodes" class="parent_li" ng-include="'tree_item_renderer'" tree-node></li>
</ul>
</script>
<ul>
<li ng-repeat="data in displayTree" ng-include="'tree_item_renderer'"></li>
关于javascript - 将参数传递给 Angular ng-include,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25565475/