Glory to Russia
Glory to Russia

Reputation: 18712

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. Therefore I need to pass $http to startup in 2 places:

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

How can I do that?

Upvotes: 0

Views: 85

Answers (1)

NiRUS
NiRUS

Reputation: 4259

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.

In your case you can apply the below logic to pass references to the functions you intend to access $http object.

Checkout the Js fiddle link

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:

<!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.

Hope this helps you!

Upvotes: 1

Related Questions