AngularJS:重复并按数字范围过滤

AngularJS: Repeat and filter by number range

本文关键字:数字 范围 过滤 AngularJS      更新时间:2023-09-26

我正在尝试格式化一个"分数"系统。我的json返回的是一个"title"和一个"score"——理想情况下,我希望它的格式如下:

100--------

标题--99

标题--91

90--------

标题-89

标题--81

80---(等)

我已经做到了,所以我的分数从高到低依次排列,但我不知道如何过滤范围,并以某种方式偷偷地在主"100、90、80"计数/标题区域添加一行。

HTML代码:

<body ng-app="myApp" ng-controller="myCtrl">
<table class="table">
<tbody>
  <tr ng-repeat="x in myData | orderBy:'title' | orderBy:'-score'">
    <td>{{x.title}}</td>
    <td>{{x.score}}</td>
  </tr>
</tbody>
</table>
</body>

AngularJS:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("scores.json").then(function (response) {
  $scope.myData = response.data;
 });
});

我认为for循环或if语句可能会起作用,但我不确定如何将其放入angularjs的选项/过滤器等中。

您可以使用模运算

您的HTML

<body ng-app="myApp" ng-controller="myCtrl">
  <table class="table">
    <tbody>
      <tr ng-repeat-start="x in myData | orderBy:'title' | orderBy:'-score'" ng-if="x.score % 10 == 0">
        <td colspan="2">x.score -----------</td>
      </tr>
      <tr ng-repeat-end>
        <td>{{x.title}}</td>
        <td>{{x.score}}</td>
      </tr>
    </tbody>
  </table>
</body>

如果你的分数是10的倍数,它将显示一个章节的标题,然后它将显示标题和分数

我在没有应用任何过滤条件的情况下就实现了这一点。但我稍微更改了您的json格式。在这里查看我的jsfiddle。

Js报价

这是我的代码

编写脚本

var myApp = angular.module('Application', []);
myApp.controller('myController', ['$scope', function($scope) {
    $scope.tabledata = [{
        title:"100",subhead:[{value:"99"},{value:"98"},{value:"97"}]
    }, {
        title:"90",subhead:[{value:"89"},{value:"88"},{value:"87"}]
    }, {
        title:"80",subhead:[{value:"79"},{value:"78"},{value:"77"}]
    }, {
        title:"70",subhead:[{value:"69"},{value:"68"},{value:"67"}]
    }];    
}]);

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="Application" ng-controller="myController">
    {{ tabledata }}
    <hr>
    <div ng-repeat="data in tabledata">
      <div id="data.title" class="title">
        {{data.title}}
      </div>
      <div ng-repeat="subHeading in data.subhead" class="subhead"> 
        {{subHeading.value}}
      </div>
    </div>
</div>

CSS

.title
{
  background-color:#ccc;
  font-weight:bold;
  font-size:24px;
  widht:100%;
  height:auto;
}
.subhead{
  background-color:#d7d7d7;  
  font-size:18px;
  widht:100%;
  height:auto;  
}