Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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

share|improve this answer
add comment

Using the following line helps to execute my method from the angularjs service:

angular.element('*[ng-app]').injector().get("MyService").GetName ();
share|improve this answer
    
See my edit using get() instead of invoke(). –  mitch Jun 27 '13 at 12:59
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.