从简单的 js 代码调用 angularjs 服务

编程入门 行业动态 更新时间:2024-10-27 13:33:41
本文介绍了从简单的 js 代码调用 angularjs 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有以下 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/wGeNG/

Here is the jsfiddle: http://jsfiddle/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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 15:03:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1004393.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   简单   js   angularjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!