从简单的 js 代码调用 angularjs 服务 [英] Call angularjs service from simple js code

查看:21
本文介绍了从简单的 js 代码调用 angularjs 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 angularjs 服务:

I have the following angularjs service:

angular.module('app.main').factory('MyService', ["$http", function ($http) {
    return new function () {

        this.GetName = function () {
            return "MyName";
        };
    };
}]);

如何从旧 js 代码中调用 MyService 中的 GetName 函数?

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

推荐答案

使用 angular.喷油器.使用您的代码,您可以执行以下操作:

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/

注意 - 在加载自定义模块之前,您需要添加ng"作为您的第一个模块,因为您的示例代码取决于 ng 模块中的 $http 提供程序.

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 - 在 OP 的回答中使用 get() 请注意,此代码是在不依赖绑定到的元素的情况下获取服务应用程序模块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 代码调用 angularjs 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆