【问题标题】:Change the order of directives based on values returned from server根据从服务器返回的值更改指令的顺序
【发布时间】:2017-10-20 07:42:06
【问题描述】:

假设我有三个组件:componentA,componentB,componentC,这些组件在我的主页中使用,在页面加载时我收到这些组件的顺序如下:

{
    "componentA": 3,
    "componentC": 2,
    "componentB": 1
}

如何在我的主页中按服务器返回的顺序放置这些指令:

<div class="container">
   <componentB></componentB>
   <componentC></componentC>
   <componentA></componentA>   
</div>

【问题讨论】:

    标签: angularjs angularjs-ng-repeat components directive


    【解决方案1】:

    您可以创建一个排序的键数组:

    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>
    

    【讨论】:

    • 使用ng-switch 不会对作用域造成问题?想象componentA 需要父控制器中的listA,它是否可以从ng-switch 内部访问?
    • 您是否将listA 作为绑定传递到ComponentA 中?那仍然有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    相关资源
    最近更新 更多