参数'myAppController'不是函数,未定义

时间:2016-03-11 15:39:12

标签: javascript angularjs dependency-injection

我想将我的服务注入我的控制器并只看到我的控制台日志(在Auth服务中),但是我收到了这个错误:参数'myAppController'不是函数,未定义。我做错了什么?

在我的main.js文件中,我有:

var myApp = angular.module('myApp',['ngRoute', 'ui.router']);

myApp.controller('myAppController', ['$scope', function($scope, AuthService) {
    console.log('controller');
    AuthService.console();
    ...

在我的services.js文件中,我有:

var myApp = angular.module('myApp',[]);

myApp.service('AuthService', function(){
    this.console = function(){
        console.log('in the AuthService');
    }
});

将我的index.html文件中的文件加载为:

    <script src="js/main.js"></script>
    <script src="js/services.js"></script>

2 个答案:

答案 0 :(得分:0)

对于注射也必须将它声明为字符串:

myApp.controller('myAppController', ['$scope', 'AuthService', function($scope, AuthService) {

答案 1 :(得分:0)

像这样定义MyApp

var myApp = angular.module("myApp", ['ngRoute', 'ui.router']);

myApp.controller('myAppController', function ($scope, ajaxService) {

        ajaxService.ajaxGetWithData(url).then(function (data) {
            $scope.Data= data;
        });

});


app.service('ajaxService', function ($http, $q) {

   this.ajaxGetWithData = function (url) {

        var deferred = $q.defer();

        $http({
            method: 'POST', url: url, data: $.param(User),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;  charset=UTF-8' },
        })
            .success(function (data) {

                if (data != null) {
                    deferred.resolve(data);
                }

            })
            .error(function (err) {

                deferred.reject(err);
            });
        return deferred.promise;
    }
});