为什么我的Angularjs服务不允许我给它打电话?

时间:2017-02-27 21:49:54

标签: javascript angularjs

我正在尝试制作一个包含常用功能的角色服务。 我在我的MVC应用程序中捆绑了代码:

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

我检查了开发人员工具是否真的带了Common.js公共文件夹:

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'
]

);

和控制器:

    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中调用它时,我得到一个Error: $injector:unpr Unknown Provider

任何人都可以在不知道我的Common.js文件的地方看到我可能做错了什么?当我将Common.js移动到Services文件夹并尝试在我的控制器中调用它时,它可以工作,但不是当它在我的公共文件夹中时。没有意义!

提前致谢!

2 个答案:

答案 0 :(得分:2)

这只是因为你正在定义你的app..twice !!!!

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个参数你正在设置你的应用..只有一个参数你只是获得对现有应用程序的引用(之前已经定义过)

答案 1 :(得分:1)

使用模块的声明时请务必小心。您基本上是将app模块重新分配给不同的实例。

angular.module('app', [dependencies]) //Constructs a module with dependencies
angular.module('app').service(...) //Associates the components (service)
                                   //with the app module.