呼叫从简单的js code angularjs服务 [英] Call angularjs service from simple js code
问题描述
我有以下angularjs服务:
I have the following angularjs service:
angular.module('app.main').factory('MyService', ["$http", function ($http) {
return new function () {
this.GetName = function () {
return "MyName";
};
};
}]);
我怎么能叫的GetName
从为MyService
功能从传统的js code?
How can I call GetName
function from MyService
from legacy js code?
推荐答案
使用 angular.injector 。用你的code,你可以做类似如下:
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();
下面是的jsfiddle: http://jsfiddle.net/wGeNG/
Here is the jsfiddle: http://jsfiddle.net/wGeNG/
注意 - 你需要的,因为你的榜样code加载自定义模块之前加上NG作为你的第一个模块依赖于$ HTTP提供这是NG模块
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.
修改 - 使用的get()
作为OP的回答但注意此code是在获取不依赖于要素服务被绑定到应用程序模块main.app。
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".
这篇关于呼叫从简单的js code angularjs服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!