简体   繁体   English

如何在AngularJS中传递对$ http的引用?

[英]How do I pass a reference to $http in AngularJS?

I have following controller definition: 我有以下控制器定义:

angular.module('myapp', [ 'ngRoute' ]).config(function($routeProvider,
$httpProvider) {

[...]
})
.controller('edit', function($scope, $http, $routeParams) {
    $scope.projectid = $routeParams.id;
    $scope.viewer = "undefined";
    $scope.mode = 'nothing';
    var projectid = $routeParams.id;
})
.directive('initCesium', function(){
    return {
        restrict: 'AEC',
        link: function(scope, element, attrs) {
            if (typeof Cesium !== "undefined") {
                startup(Cesium, scope);
            } else if (typeof require === "function") {
                require(["Cesium", "scope"], startup);
            }
        }
    }
});

I need to send a web service request in function startup . 我需要在功能startup发送Web服务请求。 Therefore I need to pass $http to startup in 2 places: 因此,我需要在两个地方将$http传递给startup

  1. startup(Cesium, scope);
  2. require(["Cesium", "scope"], startup);

How can I do that? 我怎样才能做到这一点?

Ok its straight and simple. 好吧,它简单而直接。

Below is the working code i have created that illustrates how $http object can be accessed in the link function of your directive. 以下是我创建的工作代码,这些代码说明了如何在指令的链接函数中访问$ http对象。

In your case you can apply the below logic to pass references to the functions you intend to access $http object. 在您的情况下,可以应用以下逻辑将对要访问$ http对象的函数的引用传递给您。

Checkout the Js fiddle link 检出Js小提琴链接

Javascript: Javascript:

var app = angular.module('components', [])

    app.controller("MyCtrl", ["$scope","$http", function($scope, $http){        
        $scope.ctrl = "Works!"
        $scope.http = $http;
    }]);
    app.directive('helloWorld', function () {
        return {
            restrict: 'EC',            
            link:function(scope, elemnt, attrs){
                console.log("Directive");                                                        
                scope.http.post("/echo/json/", "json=%7B%22name%22%3A%22nirus%22%7D")
                .success(function(data, status) {
                    scope.name = data.name;
                   console.log(data.name)
                }).error(function (status) {
                    console.log("Error occured")
                });
            },            
            template: '<span>Hello {{name}} : it {{ctrl}}</span>'
        }
    })

angular.module('HelloApp', ['components'])

Html: HTML:

<!doctype html>
  <html ng-app="HelloApp">
   <body ng-controller="MyCtrl">
    <hello-world></hello-world>
   </body>
  </html>

In my link function i am able to access the http object. 在我的链接函数中,我能够访问http对象。

Hope this helps you! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM