如何在异步事件后触发角度过滤器

时间:2016-10-11 10:40:40

标签: javascript angularjs promise angular-filters angular-http

我有一个基于注入值的简单角度滤波器。 我需要异步初始化值,从$http响应中接收数据。 关键在于,即使已正确设置该值,过滤器一次已经过evalueted也不会再次触发。我尝试在$scope.$apply()之后放置angular.module("app").value("deferredValue", "foo");但在这种情况下我收到错误,因为$digest已在进行中。 如何修复我的代码才能使其正常工作?



angular.module("app", [])
.value("deferredValue", "")
.filter("myfilter", ["deferredValue", function(deferredValue){
  return function(input){
    if(deferredValue == input)
      return "1234";
    else
      return "4321";
  };
}])
.controller("ctrl", ["$scope","$http", function($scope, $http){
  $scope.test = "foo";
  
  $http.get("http://www.google.com").then(function(){
    angular.module("app").value("deferredValue", "foo");
  }).catch(function(){
    angular.module("app").value("deferredValue", "foo");
  });
}])

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

<div ng-app="app" ng-controller="ctrl">
  {{test | myfilter}}
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

你应该使用statefull过滤器

filter("myfilter", ["deferredValue", function(deferredValue){
    function filter(input){
       if(deferredValue == input)
           return "1234";
       else
           return "4321";
    };
    filter.$stateful = true;

    return filter;
}])

https://docs.angularjs.org/guide/filter#stateful-filters

答案 1 :(得分:1)

使用模型,可以作为参数传递给过滤器。

app
.value("deferredObj", {value:''})
.filter("myfilter", [function(){
  return function(input, defered){
    if(defered == input)
      return "1234";
    else
      return "4321";
  };
}])
.controller("ctrl", ["$scope","http", 'deferredObj', function($scope, http, deferredObj){
  $scope.test = "foo";
  $scope.deferredObj = deferredObj;
  http.get("http://www.google.com").then(function(list){
    $scope.deferredObj.value = 'foo';
  }).catch(function(){
    $scope.deferredObj.value = 'foo';
  });
}]);

标记:

{{test | myfilter : deferredObj.value}}