How to use $ http outside the controller? in AngularJS

I want to forget "jQuery" because I like "AngularJS". However, I need to know how to use independent tasks that include AngularJS elsewhere in my application. In this case, I want to use the $ https AngularJS function to import a JavaScript file, for example.

Example (he used in jQuery ):

$.get("url.js", function(data){ eval(data) }); //ok console.info($.get); //code code code... ok 

Example (as described in AngularJS )

 //In a controller App.controller('Ctrllr', ['$http', function ($http) { $http.get("url.js").success(function(data){ eval(data); //ok }); console.info($http); //code code code.... ok }) //outside $http.get("url.js"); //$http is undefined //How to use $http here? 

As you can see in the last call, $ http is out of the process. Now I would like to know how to use the $ http class or other Angular utils outside the controller / application?

+6
source share
4 answers

Of course you can use $ http in run block

 angular.module('myModule', []) .run(function($http) {$http.get('/url').success(mySuccessCallback)} 

But you still have to use $http in the angular context (application), because injection injection requires $http service injection

+4
source

Use this:

 $http = angular.injector(["ng"]).get("$http"); 
+3
source

Thanks everyone, I think the only solution would be to declare a global variable, and then assign the $ https controller to this variable

 var myAjax; App.controller('Ctrllr', ['$http', function ($http) { myAjax = $http; }); myAjax("url.js").success(function(code){eval(code)} 

If anyone has a better solution, we will be happy. Greeting:)

+1
source

You cannot do this. But this is beautiful, you should not.

What you need to do is configure the service using the factory, to which your controllers or whatever can be accessed. A factory looks like this:

 app.factory('service', ['$http', function($http) { var service = {} service.get = function() { return $http.get('/url'); } return service. }]); 

Then you can enter this service in whatever you want, and you can call the get function from there, which will return a promise to you.

Edit: To clarify, you do not need to return a promise that you can use in your imagination.

0
source

Source: https://habr.com/ru/post/982126/


All Articles