2

I am new to angular js and trying to use directives. I want to use $http in link function of directive. Below is my code

MyApp.directive('appItem', ['$http',function() { 
  return { 
    restrict: 'E', 
    scope: { 
      transaction: '=' 
    }, 
    templateUrl: 'js/directives/appItem.html' ,

    link: function($scope, $http, element, attrs) {
            $scope.process = function(trId) {
               $http({
                    method: 'PATCH',
                    url: 'http://myapp.domain.local/api/v1/items/'+trId+'.json'
                }).
               then(function successCallback(response) {
                console.log(response);
               });
            }
        }

  }
}]);

But it gives me error:

$http is not a function
user3290349
  • 1,227
  • 1
  • 9
  • 17

2 Answers2

7

MyApp.directive('appItem', ['$http',function($http) { 
  return { 
    restrict: 'E', 
    scope: { 
      transaction: '=' 
    }, 
    templateUrl: 'js/directives/appItem.html' ,

    link: function(scope,element, attrs) {
            scope.process = function(trId) {
               $http({
                    method: 'PATCH',
                    url: 'http://myapp.domain.local/api/v1/items/'+trId+'.json'
                }).
               then(function successCallback(response) {
                console.log(response);
               });
            }
        }

  }
}]);
saikumar
  • 1,041
  • 6
  • 10
1

This is because link function is not dependency injected as the directive function.

Link function is given scope object, jQLite (jQuery) wrapped element, attributes object and optionally controller object in this specific order.

Directive function on the other hand is injected with dependencies, so placing $http there would make your code work as expected.

Prashant
  • 7,340
  • 2
  • 25
  • 24