I am using Ui-Router with my AngularJS application, and am wondering how I split my angular controllers into different files to make them much more clean.
For example:
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'
})
})
In this code, how would I make it so that my_controller could be declared in an outside file rather than declaring it at the bottom like so:
app.controller('my_controller', function($scope, $filter, $http, $timeout,$mdDialog, $stateParams) {
etc....
simply referencing the javascript file in the main HTML file and then declaring the controller with app.controller... does not seem to work.
Thanks in advance!
You need to load the files containing your controllers in your HTML before you load the file that declares your application.
<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>
Inside each controller file, you would declare a controller like this:
var Controller = function ($scope) {
}
Controller.$inject = ['$scope'];
Inside your main file after you declare the app variable:
app.controller('Controller', Controller);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With