AngularJS - '控制器不是函数:单独的控制器文件

AngularJS - 'Controller not a function: Seperate controller files

本文关键字:控制器 函数 单独 文件 AngularJS      更新时间:2023-09-26

我在我的应用程序中收到"控制器不是函数错误。

从我所读到的内容来看,最常见的问题是控制器文件未在html页面中引用 - 对我来说并非如此。

当我

将控制器包含在声明模块的同一文件中时,但是当我为每个控制器使用单独的文件时,我没有收到错误。

这是我的文件夹结构:

应用.js:

var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'assets/views/mainView.html',
        controller: 'assets/controllers/mainController.js'
    });
});

主控制器.js

var myApp = angular.module('myApp');
myApp.controller('mainController', ['$scope', function($scope){
    $scope.name = "test";
}]);

我还读到,当您声明一个模块时,数组大括号 [] 会创建一个新模块,所以我将它们从 mainController.js 中的模块中取出。

如果我这样做,它可以工作:

var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'assets/views/mainView.html',
        controller: 'mainController.js'
    });
});

myApp.controller('mainController', ['$scope', function($scope){
    $scope.name = "hi";
}]);

我已经在我的索引中引用了这样的控制器.html在 head 部分:

<script src="assets/scripts/js/app.js"></script>
<script src="assets/controllers/mainController.js"></script>

当您在另一个文件中具有控制器时,无需提供您在配置中给出的控制器的路径

    myApp.config(function ($routeProvider) {
$routeProvider.when('/', {
    templateUrl: 'assets/views/mainView.html',
     //Remove this
    //controller: 'assets/controllers/mainController.js'
     //and then try this
       controller: 'mainController'
   });
});

你在使用 IIFE 吗?如果不是,则不应分配角度模块 var myApp = angular.module('myApp');在您的mainController.js上,因为它会覆盖您的myApp变量,因为它被视为地球变量。

如果你想应用IIFE,你的代码应该是:

应用.js

    (function () {
         var myApp = angular.module('myApp', ['ngRoute']);
        myApp.config(function ($routeProvider) {
            $routeProvider.when('/', {
                templateUrl: 'assets/views/mainView.html',
                controller: 'mainController'
            });
        });
    })();

主控制器.js

    (function () {
        var myApp = angular.module('myApp');
        myApp.controller('mainController', ['$scope', function($scope){
            $scope.name = "test";
        }]);
    })();