优化ng-repeat的数量| angularJS

时间:2017-06-08 14:46:10

标签: javascript html angularjs json

我想根据给定的预定义级别将代码中的所有内容分开,从级别1到级别6,现在我的JSON读取

$scope.myJson=[{
  id: 1,
  level: 1,
  name: "any name"
},
{
  id: 2,
  level: 2,
  name: "any name"
},
{
  id: 3,
  level: 2,
  name: "any name"
}....]

现在在我的HTML中我写了类似

的内容
<div>level 1
  <div ng-repeat="prod in myJson"  ng-if="prod.level==1">{{prod.name}}
  </div>
</div>
<div>level 2
  <div ng-repeat="prod in myJson"  ng-if="prod.level==2">{{prod.name}}
  </div>
</div>

依此类推,我想只使用一个ng-repeat来根据级别过滤HTML中的所有结果,因为数千个应用程序的结果数量花费了太多时间来回复

2 个答案:

答案 0 :(得分:1)

您可以在ng重复中尝试切换案例,例如:

<div ng-repeat="prod in myJson">
   <div ng-switch-on = "prod.level">
        <div ng-switch-when="1">
             Level 1 {{prod.name}}
        </div>
        <div ng-switch-when="2">
             Level 2 {{prod.name}}
        </div>
        <div ng-switch-default>
             Another level {{prod.name}}
        </div>
  </div>
</div>

因此,您只会对数据进行一次运行。

答案 1 :(得分:1)

为了使其更通用,groupBy将为您解决此问题。

演示:

&#13;
&#13;
angular.module('app', ['angular.filter'])
  .controller('myCtrl', function($scope) {
    $scope.myJson = [{
      id: 1,
      level: 1,
      name: "any name level1"
    }, {
      id: 2,
      level: 2,
      name: "any name level2"
    }, {
      id: 3,
      level: 2,
      name: "any name level2"
    }, {
      id: 4,
      level: 2,
      name: "any name level2"
    }, {
      id: 5,
      level: 1,
      name: "any name level1"
    }, {
      id: 6,
      level: 3,
      name: "any name level3"
    }]
  });
&#13;
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
</head>

<body>
  <div ng-controller="myCtrl">

    <ul ng-repeat="(key, value) in myJson | groupBy: 'level'">
      Level- {{ key }}
      <li ng-repeat="item in value">
        {{ item.name }}
      </li>
    </ul>
  </div>
</body>

</html>
&#13;
&#13;
&#13;