0

我是 AngularJS 的新手。我正在尝试过滤reciperecipeService. 我的对象出现,但没有应用过滤器。

如果我将项目直接附加到my中$scope调用的变量,而不是使用,则过滤器将起作用。recipescontroller.jsng-repeat="recipe in recipes"

有什么建议吗?问候。

HTML

<li ng-repeat="recipe in recipeService.allRecipes | orderBy:'name':reverse">{{recipe.name}}</li>

我工厂的reciperService.service.js:

var service = {};

service.allRecipes = [];

service.getAllRecipes = function () {
  return $http.get('/api/recipes')
    .success(function (recipes) {
      service.allRecipes = recipes;
      return recipes;
    });
};
return service;

控制器声明中的controller.js:

$scope.recipeService = recipeService;
recipeService.getAllRecipes();
4

2 回答 2

0

这是一个快速的 plunker,它显示了这个工作。

http://plnkr.co/edit/QQmLpmOxUK7rl95hBdIn?p=preview

以您的方式使用 Promise 可能存在问题。也许吧,我记不得了。如果它有问题,你可以做一些不同的事情。要么使用

$q.defer()

或者

$rootScope.$broadcast('something');

更新变量

编辑

并不是说您错误地使用了 Promise,只是有时因为设置变量存在延迟并且它错过了摘要周期。

编辑 2

或者,您可以使函数成为承诺并在控制器中处理承诺,这将正确设置变量。这就是我通常做涉及 $http 请求的事情的方式。所以服务会...

service.getAllRecipts = function() {
  return $http.get(url);
}

然后在你的控制器中处理承诺

var req = recipeService.getAllRecipes();

req.success(function(data) {
  $scope.recipes = data;
}
于 2015-02-13T22:46:15.227 回答
0

好的,我解决了这个问题。我尝试了@ribsies 提供的替代方案,它们取得了与我在操作中相同的结果。食谱已发布到 html,但过滤器仍然不起作用。

我发现问题在于orderBy:'name':reverse",我需要的不是 ,而是orderBy:'-name'"。这对我来说是反向过滤的。不确定为什么会这样,但确实如此。

于 2015-02-14T01:30:35.130 回答