javascript - 为什么我的 Angularjs 服务不允许我调用它?

标签 javascript angularjs

我正在尝试创建一个包含常见功能的 Angular 服务。 我将代码捆绑在我的 MVC 应用程序中:

            bundles.Add(new ScriptBundle("~/bundles/Angular")
            .IncludeDirectory("~/app", "*.js", true));

我在开发者工具中检查了它是否确实使用 Common.js 引入了我的公共(public)文件夹:

Common.js Is second in the list

我将 Common 添加到应用程序中:

var app = angular.module('app',
[
    'JobCtrl',
    'JobSvc',
    'WebsiteCtrl',
    'WebsiteSvc',
    'myClientCtrl',
    'ClientSvc',
    'MediaCompanyCtrl',
    'MediaCompanySvc',
    'PageAlertSvc',
    'ui.bootstrap',
    'ui.bootstrap.tpls',
    'Common'
]

);

和 Controller :

    angular.module('app', ['ui.bootstrap', 'ui.bootstrap.tpls'])
.controller('JobCtrl',
        [
            'JobService',
            'WebsiteService',
            'MediaCompanyService',
            'ProductService',
            '$scope',
            '$uibModal',
            'PageAlertService',
            'Common',
            function (JobService, WebsiteService, MediaCompanyService,
                ProductService, $scope, $uibModal,PageAlertService, Common)

这就是我的 Common.js 文件的样子:

    angular.module('app')
.service('Common', function () {

    this.heyThere = function ()
    {
        console.log('Just wanted to say hey there')
    };

});

每当在我的 JobCtrl 中调用它时,我都会收到错误:$injector:unpr 未知提供商

有人能看出我可能做错了什么,它无法识别我的 Common.js 文件吗?当我将 Common.js 移动到 Services 文件夹并尝试在我的 Controller 中调用它时,它可以工作,但当它位于我的 Common 文件夹中时则不行。毫无意义!

提前致谢!

最佳答案

这只是因为您定义了您的应用程序..两次!!!!

angular.module('app', []) // this is where you re-define your app
.service('Common', function () {

    this.heyThere = function ()
    {
        console.log('Just wanted to say hey there')
    };

});

应该是:

angular.module('app')
.service('Common', function () {

    this.heyThere = function ()
    {
        console.log('Just wanted to say hey there')
    };

});

模块函数有 2 种模式.. 使用 2 个参数,您可以设置应用程序。. 使用单个参数,您只需获取对现有应用程序的引用(之前已定义)

关于javascript - 为什么我的 Angularjs 服务不允许我调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42496403/

相关文章:

javascript - Angular 2自动日期选择器表格中的日期

javascript - 附加到元素的脚本标记会在 .append() 之后的下一行之前运行吗?

javascript - 需要 cssSandpaper.js 帮助吗?

javascript - AngularJS 从作用域创建新的作用域

javascript - 使用 ng-pattern 的文本框值仅允许小数和数字?

javascript - 从 Web 配置中获取数据

javascript - 如何使用 RequireJS 同步加载脚本

javascript - 这个 Angular 误差是多少?

javascript - AngularJS http get 与 settimeout 逻辑

javascript - 删除了以下划线开头的 Firebase 数据库键