如何使用Angularjs从json中对整数值进行排序

时间:2015-02-19 07:30:07

标签: angularjs angularjs-orderby

我正在尝试在角度中使用orderBy功能,并按RollNo排序,但它不起作用请检查下面的代码

SCRIPT

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>

2 个答案:

答案 0 :(得分:1)

你正在做data.RollNo = parseFloat($data.RollNo);无法正常工作,你需要循环抛出对象并做到这一点。

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

<强> CODE

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

希望这可以帮到你。感谢。

答案 1 :(得分:0)

好像你的代码不正确

<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