Search code examples
angularjsangular-filters

inject dependecy to custom filter angularJS


I want to inject $http on my custom filter to use it on my view:

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;

    }

}]);

I got error that $http is not defined

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)

Where should I inject the "$http" dependecy ?


Solution

  • You injected the dependency but not used as a argument in function

    Don't use filter for this, you can write your code in controller

    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;
            });
        }
    }]);