我正在使用Ui-Router和我的AngularJS应用程序,我想知道如何将角度控制器分成不同的文件以使它们更加干净。
例如:
var app = angular.module('myApp', ["xeditable", 'ngRoute','ngSanitize',
'ngAnimate', 'ngAria', 'ngMaterial','ngFileUpload','ui.router']);
app.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/my_requisitions/list");
$stateProvider
.state('my_requisitions', {
url: "/my_requisitions",
templateUrl: "../../../partials/requisitions/my_requisitions.ctp",
//controller: 'my_controller'
})
.state('my_requisitions.list', {
url: "/list",
templateUrl: "../../../partials/requisitions/my_requisitions.list.ctp",
//controller: 'my_controller'
})
.state('my_requisitions.add', {
url: "/add/:type",
templateUrl: "../../../partials/requisitions/my_requisitions.add.ctp",
controller: 'my_controller'
})
.state('manage_requisitions', {
url: "/manage_requisitions",
templateUrl: "../../../partials/requisitions/manage_requisitions.ctp"
})
.state('manage_requisitions.list', {
url: "/list",
templateUrl: "../../../partials/requisitions/manage_requisitions.list.ctp",
controller: 'manage_controller'
})
})
在这段代码中,我将如何制作它以便my_controller可以在外部文件中声明,而不是像下面那样在底部声明:
app.controller('my_controller', function($scope, $filter, $http, $timeout,$mdDialog, $stateParams) {
etc....
简单地引用主HTML文件中的javascript文件,然后用app.controller声明控制器...似乎不起作用。
提前致谢!
答案 0 :(得分:3)
在加载声明应用程序的文件之前,需要在HTML中加载包含控制器的文件。
<script src="/path/to/angular.js"></script>
<script src="/path/to/controller1.js"></script>
<script src="/path/to/controller2.js"></script>
<script src="/path/to/yourapp.js"></script>
在每个控制器文件中,您将声明一个这样的控制器:
var Controller = function ($scope) {
}
Controller.$inject = ['$scope'];
声明app变量后,在主文件中:
app.controller('Controller', Controller);
答案 1 :(得分:0)
您可以将控制器编写在单独的文件中,并在包含应用程序文件后将其包含在HTML文件中
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/Demo.js"></script>
<script src="~/Scripts/DemoController.js"></script>
<title>Demo</title>
</head>
<body>
<div ng-app="demoApp">
<div ng-controller="demoController">
<span>{{dummyData}}</span>
</div>
</div>
</body>
</html>
Demo.js的代码
var demoApp = angular.module('demoApp',[]);
DemoController.js的代码
demoApp.controller('demoController', function($scope) {
$scope.dummyData = "hello from demo app";
});