【问题标题】:how to sort interger value from json using Angular.js如何使用Angularjs对json中的整数值进行排序
【发布时间】:2015-02-19 07:30:07
【问题描述】:

我正在尝试在 Angular 中使用 orderBy 功能,并通过 RollNo 订购,但它不起作用请检查下面的代码

脚本

var countryApp = angular.module('countryApp', []);
countryApp.controller('CountryCtrl', function ($scope, $http){
  $http.get('http://localhost/angular/jason/index.php').success(function(data) {
      $scope.countries = data;
      data.RollNo = parseFloat($data.RollNo);
  });
});

JSON

data = [{
    "Name": "Kamal",
    "RollNo": "20",
    "Class": "Class 12"
}, {
    "Name": "Amar",
    "RollNo": "12",
    "Class": "Class 10"
}, {
    "Name": "Rajesh",
    "RollNo": "9",
    "Class": "Class 7"
}]

HTML

 <body ng-controller="CountryCtrl">
  <input type="text" ng-model="name">
    <table>
      <tr>
        <th>Name</th>
        <th>Roll Number</th>
        <th>Class</th>
      </tr>
      <tr ng-repeat="country in countries | filter:name | orderBy:'RollNo'">
        <td>{{country.Name}}</td>
        <td>{{country.RollNo}}</td>
        <td>{{country.Class}}</td>
      </tr>
    </table>
  </body>

【问题讨论】:

    标签: angularjs angularjs-orderby


    【解决方案1】:

    你正在做的data.RollNo = parseFloat($data.RollNo); 不起作用,你需要循环抛出对象并执行它。

    您需要先将国家对象的RollNo属性转换为数字,然后才能应用orderBy

    代码

    var newArray = [];
    angular.forEach($scope.countries, function(val, index){
      newArray.push(val);
      newArray[newArray.length-1].RollNo = parseInt(newArray[newArray.length-1].RollNo);
    });
    $scope.countries = newArray;
    

    Working Plunkr

    希望这可以帮助你。谢谢。

    【讨论】:

    • @Kamal 很高兴为您提供帮助。谢谢:)
    【解决方案2】:

    您的代码似乎不正确

    <tr ng-repeat="country in countries | filter:name | orderBy:'RollNo'">
    

    您已在单引号中使用了orderBy:'RollNo'RollNo。就是这个问题

    改成

    <tr ng-repeat="country in countries | filter:name | orderBy:RollNo">
    

    它会正常工作的。

    这里是Demo Plunker

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-30
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多