2016-01-24 67 views
1

的链接函数中的函数我是新来的角js和尝试使用指令。 我想在指令的链接函数中使用$ http。 下面是我的代码

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

    } 
}]); 

但它给我的错误:

$http is not a function 

回答

6

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

 
    } 
 
}]);

+0

更新您的代码 – saikumar

1

这是因为链接功能不依赖注入的指导作用。

链接函数被赋予作用域对象,jQLite(jQuery)打包的元素,属性对象和可选的控制器对象。

另一方面,指令函数注入了依赖关系,因此在其中放置$ http将使您的代码按预期工作。

+0

您的意思是? MyApp.directive('appItem',[function($ http){...}] – user3290349

+0

准确的说,在链接函数中你可以访问$ http。 – Prashant