2016-01-24 64 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