javascript - 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 send web service request in function startup. therefore need pass $http startup in 2 places:

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

how can that?

ok straight , simple.

below working code have created illustrates how $http object can accessed in link function of directive.

in case can apply below logic pass references functions intend access $http object.

checkout 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}} : {{ctrl}}</span>'         }     })  angular.module('helloapp', ['components']) 

html:

<!doctype html>   <html ng-app="helloapp">    <body ng-controller="myctrl">     <hello-world></hello-world>    </body>   </html> 

in link function able access http object.

hope helps you!


Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -