angular.js ng-repeat - 检查条件是否为真,然后使用另一个集合 [英] angular.js ng-repeat - check if conditional is true then use another collection
问题描述
我想知道是否可以检查在 ng-repeat
中使用什么集合?
I'm wondering is it possible to check what collection to use inside ng-repeat
?
例如,在我的控制器中,我有 2 个从服务器获取的数据数组,现在我使用 ng-switch
在它们之间切换,检查这个 jsbin - http://jsbin.com/diyefevi/1/edit?html,js,output
For example, in my controller I have 2 arrays of data fetched from server, now I use ng-switch
to switch between them, check this jsbin - http://jsbin.com/diyefevi/1/edit?html,js,output
问题是我实际应用程序中的这些 li
视图很大但非常相似..所以我真的想使用 1 ng-repeat
代替共 2 个.
The problem is that these li
views in my real application are big but very similar.. so I really would like to use 1 ng-repeat
instead of 2.
所以我想知道在 Angular 中是否可以使用 ng-repeat="book in if list==='adultBooks' AdultBooks else childBooks"
之类的东西?
So I wonder if something like ng-repeat="book in if list==='adultBooks' adultBooks else childBooks"
is possible in Angular?
谢谢!
推荐答案
试试这个...
在您的控制器
$scope.getDataSource=function(condition){
if(condition){ return dataSource1; }
return dataSource2;
};
在您的HTML
ng-repeat="book in getDataSource(/*condition*/)
MVVM 模式建议将我们的逻辑始终放在控制器中,而不是放在视图中(HTML).如果您发现自己在视图中添加了逻辑",那么可能还有另一种更好"的方法来做到这一点.
MVVM Pattern advises to put our logic always in the controller and not in the view(HTML). If you ever find yourself adding "logic" in your view probably there is an alternate "better" way to do it.
但为了好玩",您也可以这样做:
But just for "fun" you can do this too:
ng-repeat="book in {true: adultBooks, false: childBooks}[list==='adultBooks']"
像这样:
<li ng-repeat="book in {true: childBooks, false:adultBooks}[list==='childBooks']">{{book.name}
这是完整的示例:
http://jsbin.com/diyefevi/5/edit?html,js,输出
这篇关于angular.js ng-repeat - 检查条件是否为真,然后使用另一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!