AngularJS在返回控制器之前预先对工厂结果进行排序

时间:2018-02-01 15:56:39

标签: angularjs sorting controller promise factory

如何预先对发送回控制器的工厂的结果进行排序?我已尝试在主工厂功能中,作为单独的工厂功能,并在控制器内,因为$ scope填充了工厂结果 - 在每种情况下都失败了。我没想到什么?

.factory('Products', function($http,promise1,promise2,promise3) {
   var prods = [] ;  // i changed to a global var here
   return {
      //prods: [],  // i also tried as an internal object using (this.prods)
      getProds: function() {
        $q.all([promise1(),promise2(),promise3()]).then(function(response) {
           for (var y=0;y<response.length;y++) {
              // this.prods.push(response[y]) //
              prods.push(response[y]) ; // array of objects
              // need to sort prods based on object.price or object.vendor
           }
           // I tried here, but didn't work either:
           this.sortProds('price') ;
        }
      },
      sortProds: function(key) {
        // this.prods.sort(function(a,b) {   
        prods.sort(function(a,b) {
          var x = a[key]; var y = b[key] ;
          if (key == "vendor") {
            return ((x<y) ? -1 : ((x > y) ? 1: 0)) ;
          } else {
            return parseFloat(a[key]) - parseFloat(b[key]) ;
          }
        }) ;
      }
   }
})

.controller('ProductsController',function($scope,Products) {
   $scope.prods = Products.getProds() ;
   // or should I be sorting here in the controller?
})

0 个答案:

没有答案