使用 ng-view 时控制器可以在单独的文件中吗?

Can a controller be in a seperate file when using ng-view?

目前正在学习AngularJS。我制作了一个通过 ng-view 指令显示的 'hello world' 应用程序。到目前为止一切顺利!

我的文件是这样排序的:

- WebContent *(root)*
> - controllers *(folder)*
>> - controllers.js
> - views *(folder)*
>> - view1.html
>> - view2.html
> - index.html

路由配置如下所示:

function routeConfig($routeProvider){
$routeProvider.when('/', 
{
templateUrl: "views/view1.html",
controller: "View1Ctrl"
}
).when("/view/:id", 
{
templateUrl: "views/view2.html",
controller: "View2Ctrl"
}
).otherwise(
{
redirectTo: "/"
});
};

app.controller("View1Ctrl", function($scope) {
$scope.message = "Hello World1";
}
[... etc. ...]

正如我之前提到的:这工作得很好。然而,事情可能会变得更加复杂。控制器可以包含更多功能等。是否可以将这些控制器放在外部文件中?所以它看起来像这样:

- WebContent *(root)*
> - controllers *(folder)*
>> - controllers.js
>> - view1-controller.js
>> - view2-controller.js
> - views *(folder)*
>> - view1.html
>> - view2.html
> - index.html

我已经尝试将这些文件简单地导入到索引中:

<script src="controllers/view1-controller.js"></script>

但这似乎没有用。 (它给我留下了空白页。)希望有人能帮助我!

达格·罗伯特,

当然可以,更推荐!我想向您推荐这个 Plunkr

基本上你可以这样做:

(function() {
  angular
    .module('plunker')
    .directive('helloWorld', function() {
      return {
        scope: true,
        restrict: 'E',
        controller: 'HelloWorldController',
        controllerAs: '$ctrl',
        templateUrl: 'app/directives/hello-world/template.html'
      };
    })
})();

重要提示:

  • 要创建一个新模块,您写:angular.module('name', dependencies);。其中依赖项是一个数组。
  • 要检索您不编写依赖项的相同模块: angular.module('name')。这将简单地 get 模块
  • WebContent(根目录)

    • 控制器(文件夹)

    Home.js

    Employee.js

    • 浏览量 *(文件夹)

    view1.html

    view2.html

    • index.html

这是index.js

var myApp = angular.module('myApp'); 这是单独的家庭控制器 (Home.js)

myApp.controller('HomeCtrl', function ($scope) { }

myApp.config(["$routeProvider",function ($routeProvider) {
$routeProvider
.when("/Employees", {
    templateUrl: "templates/Employees/Employee.cshtml",
    controller: "EmployeeController"
})
.when("/Home", {
    templateUrl: "templates/Home/Home.cshtml"
})

.when("/EmployeeProgress", {
templateUrl: "templates/EmployeeStats/EmployeeStats.cshtml"
 })
.otherwise({
    templateUrl: "templates/Home/Home.cshtml"

});

}]);

这是单独的 employee.js

myApp.controller('EmployeeController',function ($scope) { }

这是单独的 Home.js

myApp.controller('HomeController',function ($scope) { }