简体   繁体   中英

Error: Argumentcontroller is not a function, got undefined

I am kicking the tires using Angular and having issues getting my sandbox app running. I want to implement a simple controller using a service. However, I am receiving the following error:

Error: Argument 'UserController' is not a function, got undefined

The files are referenced on the page in the order listed. webConfig.JS

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

UserController.JS

app.controller('UserController', function ($scope, UserService) {
    // Define the model properties. The view will loop
    // through the services array and genreate a li
    // element for every one of its items.

    $scope.services = [
        {
            name: 'Web Development',
            price: 300,
            active: true
        }, {
            name: 'Design',
            price: 400,
            active: false
        }, {
            name: 'Integration',
            price: 250,
            active: false
        }, {
            name: 'Training',
            price: 220,
            active: false
        }
    ];

    $scope.LogInfo = {
        UserName: 'username',
        Password: 'password'
    };

    $scope.ProcessLogin = function (Info) {
        UserService.GetLoginStatus(Info);
    };

    $scope.toggleActive = function (s) {
        s.active = !s.active;
    };

    // Helper method for calculating the total price

    $scope.total = function () {

        var total = 0;

        // Use the angular forEach helper method to
        // loop through the services array:

        angular.forEach($scope.services, function (s) {
            if (s.active) {
                total += s.price;
            }
        });

        return total;
    };
});

UserService.JS

app.service('UserService', function () {
    this.GetLoginStatus = function (Info) { 
        alert(JSON.stringify(Info)) 
    };
});

Because your app is spanning multiple files I would not add your controllers to your module via the app variable, instead look up the module via its name...

Change:

app.controller('UserController', function ($scope, UserService) {
&
app.service('UserService', function () {

To:

angular.module('app').controller('UserController', function ($scope, UserService) {
 &
angular.module('app').service('UserService', function () {

I figured it out. The problem actually originated from my HTML. Once I added ng-app="app" where I was referencing the controller then everything worked.

<body ng-controller="UserController" ng-app="app">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM