根据服务器返回的值更改指令的顺序
Change the order of directives based on values returned from server
假设我有三个组件:componentA
、componentB
、componentC
,这些组件在我的主页中使用,在页面加载时我收到这些组件的顺序,例如所以:
{
"componentA": 3,
"componentC": 2,
"componentB": 1
}
如何在我的主页中按服务器返回的顺序放置这些指令:
<div class="container">
<componentB></componentB>
<componentC></componentC>
<componentA></componentA>
</div>
您可以创建一个排序的键数组:
var list = {
"componentA": 3,
"componentC": 2,
"componentB": 1
}
var listSorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]})
console.log(listSorted) // ["componentB", "componentC", "componentA"]
然后就可以使用ng-switch了(https://docs.angularjs.org/api/ng/directive/ngSwitch)
同时使用 ng-repeat (https://docs.angularjs.org/api/ng/directive/ngRepeat) 迭代数组。允许您在每个组件上编写条件来确定渲染它。
<div ng-repeat="componentName in $ctrl.listSorted track by $index"
ng-switch="componentName">
<componentA ng-switch-when="componentA">...</componentA>
<componentB ng-switch-when="componentB">...</componentB>
<componentC ng-switch-when="componentC">...</componentC>
</div>
假设我有三个组件:componentA
、componentB
、componentC
,这些组件在我的主页中使用,在页面加载时我收到这些组件的顺序,例如所以:
{
"componentA": 3,
"componentC": 2,
"componentB": 1
}
如何在我的主页中按服务器返回的顺序放置这些指令:
<div class="container">
<componentB></componentB>
<componentC></componentC>
<componentA></componentA>
</div>
您可以创建一个排序的键数组:
var list = {
"componentA": 3,
"componentC": 2,
"componentB": 1
}
var listSorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]})
console.log(listSorted) // ["componentB", "componentC", "componentA"]
然后就可以使用ng-switch了(https://docs.angularjs.org/api/ng/directive/ngSwitch) 同时使用 ng-repeat (https://docs.angularjs.org/api/ng/directive/ngRepeat) 迭代数组。允许您在每个组件上编写条件来确定渲染它。
<div ng-repeat="componentName in $ctrl.listSorted track by $index"
ng-switch="componentName">
<componentA ng-switch-when="componentA">...</componentA>
<componentB ng-switch-when="componentB">...</componentB>
<componentC ng-switch-when="componentC">...</componentC>
</div>