Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call angularjs service from simple js code

I have the following angularjs service:

angular.module('app.main').factory('MyService', ["$http", function ($http) {     return new function () {          this.GetName = function () {             return "MyName";         };     }; }]); 

How can I call GetName function from MyService from legacy js code?

like image 866
Dor Cohen Avatar asked Jun 26 '13 12:06

Dor Cohen


People also ask

Which of the below command will help to call AngularJS function using JavaScript?

How to call angularJS function from javascript/jquery - Dot Net Concept. You can call your angularJS function from javascript or jquery with the help of angular. element().

Can you use JavaScript for angular?

Yes. Angular does use . ts files by default. But if you write simple javascript code in them it will still work.


2 Answers

Use angular.injector. Using your code you can do something like the following:

angular.module('main.app', []).factory('MyService', ['$http', function ($http) {     return new function () {          this.GetName = function () {             return "MyName";         };     }; }]);   angular.injector(['ng', 'main.app']).get("MyService").GetName(); 

Here is the jsfiddle: http://jsfiddle.net/wGeNG/

NOTE - You need to add "ng" as your first module before loading your custom module since your example code depends upon $http provider which is in the ng module.

EDIT - Using get() as in OP's answer but note this code is fetching the service without relying upon the element being bound to the app module "main.app".

like image 102
mitch Avatar answered Sep 22 '22 01:09

mitch


For me it worked with:

angular.element(document.body).injector().get("MyService") 

I got 'Unknown provider' error when tried this:

angular.injector(['ng', 'main.app']).get("MyService") 

and as i am using jqLite, i can't do

angular.element('*[ng-app]') 

because selectors are not supported by jqLite, but i got [Dor Cohen] idea. My directive ng-app is on my body tag, then i can use:

angular.element(document.body).injector().get("MyService") 

or

angular.element(document).find('body').injector().get("MyService") 
like image 41
Gilson Avatar answered Sep 24 '22 01:09

Gilson