Call angularjs service from simple js code

我的未来我决定 提交于 2019-11-26 19:24:35

问题


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?


回答1:


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




回答2:


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



回答3:


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

angular.element('*[ng-app]').injector().get("MyService").GetName ();



回答4:


Here's a utility method that I use :

function getService(name, element) {
    element = element || '*[ng-app]';
    return angular.element(element).injector().get(name);
}

getSrv("name-of_service", document.body)



来源:https://stackoverflow.com/questions/17319784/call-angularjs-service-from-simple-js-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!