【问题标题】:nested list based on type column in angularjs基于angularjs中类型列的嵌套列表
【发布时间】:2016-07-26 11:56:04
【问题描述】:

我有一个 angularjs sample here,其中包含一个示例数组

 $scope.myarr = [
{id: 1, name: 'foo',type: 1},
{id: 2,name: 'bar',type: 1},
{id: 3,name: 'quad',type: 2},
{id: 4,name: 'cab',type: 2},
{id: 5,name: 'baz',type: 2},
{id: 6,name: 'cad',type: 3}
];

我自己尝试使用ng-repeat 创建一个列表,可以这样做

<ul ng-repeat="x in myarr">
<li>{{x.id}}. {{x.name}} - Type {{x.type}}</li>
</ul>

但实际上想要的是一个基于x.type 列的嵌套列表,

  1. 类型 1
    • 1。富
    • 2。酒吧
  2. 类型 2
    • 3。四边形
    • 4。出租车
    • 5。巴兹
  3. 类型 3
    • 6。 cad

如何使用angularjs来完成?

【问题讨论】:

    标签: javascript arrays angularjs json list


    【解决方案1】:

    利用内部ng-repeatfilter / unique

    AngularJS 默认不包含唯一的过滤器。您可以使用角度过滤器中的一个。只需包含 JavaScript

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>
    

    并在您的应用中包含依赖项:

    var app = angular.module('myApp', ['angular.filter']);
    

    更多关于https://docs.angularjs.org/api/ng/directive/ngRepeat的信息

    <div id="app" ng-app="myApp" ng-controller="myCtrl">
      <ul ng-repeat="x in myarr | unique:'type'">
          <li>{{x.id}}. {{x.name}} - Type {{x.type}}</li>
          <ul>
            <li ng-repeat="y in myarr | filter:type=x.id"> 
              {{y.name}}
            </li>   
          </ul>
      </ul>
    </div>
    
    angular.module('myApp', []).controller('myCtrl', function($scope) {
     $scope.myarr = [
        {id: 1, name: 'foo',type: 1},
        {id: 2,name: 'bar',type: 1},
        {id: 3,name: 'quad',type: 2},
        {id: 4,name: 'cab',type: 2},
        {id: 5,name: 'baz',type: 2},
        {id: 6,name: 'cad',type: 3}
      ];
    });
    

    将给出结果:

    Type 1
        1. foo
        2. bar
    Type 2
        3. quad
        4. cab
        5. baz
    Type 3
        6. cad
    

    查看更新后的Fiddle

    【讨论】:

    • 我已经重新分叉了 - 这个链接有效吗? jsfiddle.net/2y460yvp 或者你的意思是别的不工作?
    • 成功了:jsfiddle.net/mpsbhat/tpt8g8xx/4。需要包含外部角度过滤器文件才能工作unique 谢谢:)
    • 太好了,刚刚更新了我的答案,而你自己找到了它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 2023-03-22
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    相关资源
    最近更新 更多