2017-04-23 190 views
-2

我要注入$ HTTP在我的自定义过滤器,使用它在我的观点:注入dependecy自定义过滤器angularJS

angular.module('demo').filter('quesByID',['$http', function() { 
var input=""; 
    return function(input) { 
     $http.get("http://localhost:3003/api/quiz/"+input).then(function(reponse){ 
      input=reponse.data; 
     }); 
      return input; 

    } 

}]); 

我有错误$ HTTP是没有定义

angular.js:13920 ReferenceError: $http is not defined 
    at getQuestionById.js:4 
    at fn (eval at compile (angular.js:14817), <anonymous>:4:198) 
    at regularInterceptedExpression (angular.js:16043) 
    at expressionInputWatch (angular.js:15948) 
    at Scope.$digest (angular.js:17515) 
    at Scope.$apply (angular.js:17790) 
    at done (angular.js:11831) 
    at completeRequest (angular.js:12033) 
    at XMLHttpRequest.requestLoaded (angular.js:11966) 

在哪里我应该注入“$ http”的依赖吗?

+2

实际上你需要提供'$ http'作为该功能的参数;即'函数($ http){' – Claies

+2

为什么你使用这个过滤器? – charlietfl

+0

您正在滥用筛选器。改为使用服务。在控制器中这样做(如答案所示)是一种快速解决方法,但很难称之为最佳实践。 – estus

回答

0

您注射dependency但不能用作argument在功能

不要使用过滤器,您可以在控制器编写代码

angular.module('demo').controller('controller',['$http', function($http) { 
    $scope.data; 
    $scope.getData = function(input) { 
     $http.get("http://localhost:3003/api/quiz/"+input).then(function(reponse){ 
      $scope.data = reponse.data; 
     }); 
    } 
}]); 
+0

'$ http'是**异步**这根本行不通 – charlietfl

+0

我修复了用户的主要问题,并非全部。但是现在我更新了所有的东西 – Gaurav

+0

仍然无法工作......您将如何使用从过滤器返回的承诺?还要考虑在视图中使用这种过滤器时会发生多少次这样的请求。整个事情没有意义 – charlietfl

相关问题