使用orderBy进行Angularjs排序对我不起作用

时间:2015-02-14 10:44:45

标签: javascript angularjs sorting angularjs-ng-repeat angular-ui

我正在尝试根据评分,定价和总计数对我的主页列表进行排序。不幸的是没有为我工作,我是angularjs的新手。 这里我有我的HTML代码。实际上它正在对事物进行排序,但不是按顺序排序。 - >当用户点击价格btn时,他应该首先以最高价格回家,然后降低,最低等等(5000,4000,3000)如果他再次点击那么订单必须是(3000,4000,5000)。总计数和评级类似的东西。我还创建了plunker来编辑你的建议。请编辑并提供工作链接。这是 demoForEdit

//html code
<body ng-controller="MainCtrl as ctrl">
    <div class="col-md-offset-2">
      <button ng-click="orderByPopularity='total_counts'; reverseSort = !reverseSort" class="btn btn-sm btn-info">sort on total counts </button>
      <button  ng-click="orderByPopularity='price'; reverseSort = !reverseSort" class="btn btn-sm btn-danger">sort on Price</button>    
      <button  ng-click="orderByPopularity='avg'; reverseSort = !reverseSort" class="btn btn-sm btn-success">sort on ratings</button>    
    </div>
  <br>
<div ng-repeat="home in homes | orderBy:orderByPopularity:reverseSort">
  <div class="panel panel-primary  ">
    <div class="panel-heading">
      Home name: {{home.home_name}}
    </div>
      <div class="panel-body">
        <div class="panel panel-body">
          <table>
          <p>total counts:{{home.total_counts}}</p>
          <p>city:{{home.city}}</p>
          <p>Price:{{home.price}}</p>
          <div ng-repeat="rate in rating">
          <!--  looping inside ng-repeat rating is seprate data but has home id-->
            <div ng-if="rate.home_id==home.id">
            Home raintgs:{{rate.avg}}  
          </div>
        </div>
      </div>
    </div>
  </div>  
</div>

//My app.js code
var app = angular.module('plunker', []);
    app.controller('MainCtrl', function($scope) {
      $scope.homes=[{"id":"48","home_name":"Swastik","city":"Banglore","zipcode":"888888","total_counts":"1","price":"5000"},
    {"id":"49","home_name":"Khushboo","city":"Chennai","zipcode":"456786","total_counts":"17","price":"3333"},
    {"id":"50","home_name":"Raj","city":"Hydrabad","zipcode":"123455","total_counts":"2","price":"20000"}];
    $scope.orderByPopularity ='total_counts';
    $scope.reverseSort = true;
    $scope.rating=[{"home_id":"48","avg":"3.5"},
    {"home_id":"49","avg":"2"},
    {"home_id":"50","avg":"4"}
    ];
    });

1 个答案:

答案 0 :(得分:1)

它确实排序,但您的total_counts值是字符串,因此它按字典顺序排序。如果您想按编号排序,我假设您这样做,您需要删除引号并将其值作为数字本身,即:"total_counts":17等。

编辑:已修改,因此您可以将值保存为字符串(在自定义排序功能中)。

对于avg评级排序,您不能这样做,因为您的订购位于$scope.homes,并且此阵列的对象没有{{1 \ n} }属性,这是您的其他数组的属性 - avg。 要按该属性进行排序,您必须创建自己的自定义函数。

$scope.ratings

在HTML中:

$scope.myValueFunction = function(o) {

   if ($scope.orderByPopularity == "avg") {
     var obj;
     for (var i = 0; i < $scope.rating.length; i++) { 
        if ($scope.rating[i].home_id == o.id) {
          obj = $scope.rating[i]
        }
     }
     return obj.avg;
   }
   else  {
     return parseInt(o[$scope.orderByPopularity]); 
   }

};

关于演示,请看这个Plunker