角度未排序数据

Angular not ordering data

本文关键字:数据 排序      更新时间:2023-09-26

我一直在尝试让angular js为我的数据排序。但遗憾的是,不起作用

我正在从firebase检索数据(https://boiling-inferno-4886.firebaseio.com/champion)并使用node js将其发送到控制器。

控制器代码

var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {

// Pulls list of games
$scope.pullGame = function() {
  console.log("Here");
  $http.get('/getGameData').success(function(response) {
    console.log(response);
    $scope.championlist = response;
  });
};  
}]);

然后使用ng重复显示信息

<!DOCTYPE>
<html ng-app="myApp">
<head>
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<title>DevCha</title>
</head>
<body>
<div class="container"  ng-controller="AppCtrl">
<input class="form-control" ng-model="game.name">
<button class="btn btn-info" ng-click="pullGame()">Update</button>
<h1>DevCha</h1>
<table class="table">
    <thead >
    <tr>
        <th>Champion Name</th>
        <th>Wins</th>
        <th>Losses</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="champion in championlist|orderBy: 'name'">
        <td>{{champion.name}}</td>
        <td>{{champion.wins}}</td>
        <td>{{champion.losses}}</td>
    </tr>
    </tbody>
</table>
</div>

<script src="controllers/controller.js"></script>
</body>
</html>

我尝试过使用firebase对数据进行排序,但也不起作用(这很奇怪)。但我很高兴,如果任何一个能为我分类(角或火球)

节点Js将数据推送到角度的代码

app.get('/getGameData', function(req, res){
    var ref = new Firebase("https://boiling-inferno-4886.firebaseio.com/champion");
    ref.once("value", function(snapshot) {
      // Success
      console.log(JSON.stringify(snapshot.val()));
      res.json(snapshot.val());
    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
      //callback("Failure", null);
    });
});

Sample_Data-1:{name:"Jim",赢:10,输:5},2:{name:"Fred",胜:8,输:6}(实际数据可在防火基地链接中找到)

tl:dr我需要对我的数据进行排序,我尝试使用firebase的内置方法对其进行排序,并使用angular的|orderBy,但两者都不起作用

我们确实需要查看这些数据,但由于我之前遇到过这个问题,以下是我的答案。

正如您在文档中看到的,orderBy只对数组进行排序。(key,value)语法适用于对象。也许将你的字典转换为数组就可以了。

如果没有,您可以为自己编写一个过滤器。看看这个过滤器:

app.filter('orderObjectBy', function () {
  return function (items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function (item) {
        filtered.push(item);
    });
    filtered.sort(function (a, b) {
        return (a[field] > b[field] ? 1 : -1);
    });
    if (reverse) filtered.reverse();
    return filtered;
  };
});

然后你可以这样使用它:

<div class="item" ng-repeat="item in items | orderObjectBy:'position'">
</div>

顺便说一下,你可以这样更改订单:

<ul>
  <li ng-repeat="item in items | orderObjectBy:'color':true">{{ item.color }</li>
</ul>

false为升序,true为降序