AngularJS按字段值排序

时间:2015-10-19 10:29:24

标签: angularjs angularjs-orderby

我要做的是按字段值对数据进行排序。

mAdapter.notifyDataSetChanged();

在html文件中我有选择框和3个选项,分别叫咖啡冰咖啡

如果我选择咖啡应该像这样排序

$scope.testarr = [{"id":"1","name":"coffee"},
                  {"id":"2","name":"tea"},
                  {"id":"3","name":"coffee"},
                  {"id":"4","name":"ice coffee"}]

如果我选择茶应该像这样排序

   $scope.testarr = [{"id":"1","name":"coffee"},
                      {"id":"3","name":"coffee"},
                      {"id":"2","name":"tea"},
                      {"id":"4","name":"ice coffee"}]

我试图使用订单,但不知何故它确实无法运作

   $scope.testarr = [
                      {"id":"2","name":"tea"},
                      {"id":"1","name":"coffee"},
                      {"id":"3","name":"coffee"},
                      {"id":"4","name":"ice coffee"}]

1 个答案:

答案 0 :(得分:0)

它确实有效。确保您的ng-repeat有权访问$scope.testarr(即在$scope上使用正确的控制器或指令进行宣传。



angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.testarr = [{
      "id": "1",
      "name": "coffee"
    }, {
      "id": "2",
      "name": "tea"
    }, {
      "id": "3",
      "name": "coffee"
    }, {
      "id": "4",
      "name": "ice coffee"
    }];
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="ctrl">
    <div ng-repeat="item in testarr | orderBy: 'name'">
      {{item.id}} ------ {{item.name}}
    </div>
  </div>
</div>
&#13;
&#13;
&#13;