如何在http请求中应用自定义过滤器?

时间:2014-07-09 01:06:22

标签: javascript html angularjs

我正在尝试从http请求中应用过滤器。

我有类似

的东西

HTML

<div ng-repeat="product in products | testFilter:5 "> {{product.title}} </div>

JS

app.controller('test', function($scope, $filter){
   myService.get('api/v1/products/?id=1').success(function(data) {
       $scope.products = data;    

   })
}

app.filter('testFilter', function() {
      return function(products, item) {             
          //codes...
          var t = products.length
      }
})

过滤器工作&#34; AFTER&#34;我从myService获得了数据。但是,在加载数据时,我不断获得'Cannot read property 'length' of undefined'。我知道这是因为数据仍在加载。我该如何解决这个问题?感谢。

1 个答案:

答案 0 :(得分:2)

在进行ajax调用之前,您只需要初始化$ scope.products。

像: $scope.products = []; 应该这样做!

相关问题