我正在使用 Ui-Router使用我的 AngularJS 应用程序,我想知道如何将我的 Angular Controller 拆分成不同的文件以使它们更干净。
例如:
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 声明 Controller ......似乎不起作用。
提前致谢!
最佳答案
在加载声明应用程序的文件之前,您需要在 HTML 中加载包含 Controller 的文件。
<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>
在每个 Controller 文件中,您可以像这样声明一个 Controller :
var Controller = function ($scope) {
}
Controller.$inject = ['$scope'];
声明应用程序变量后在主文件中:
app.controller('Controller', Controller);
关于javascript - 将 AngularJS Controller 分离到单独的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31879050/