I have a large AngularJs application and am struggling with route injection/organization.
Most applications ( from what I've seen ) define all the routes in one big file like https://github.com/IgorMinar/foodme/blob/master/app/js/app.js#L7
My routes are rather complex, for example:
app.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when('/navigation/:id', {
templateUrl: 'app/admin/nav/navigation.tpl.html',
controller: 'NavigationCtrl',
title: 'Navigation Config',
resolve: {
nav: function($route, NavModel) {
return NavModel.findOne($route.current.params.id);
},
reports: function($route, ReportsModel) {
return ReportsModel.findAll($route.current.params.id);
}
}
});
}]);
since they are complex and pretty coupled to the controller, my route definition page would be HUGE and very confusing.
Is there a better way to declare the routes? Can you just declare a short version and then extend on it later when that controller is injected?
You can configure $routeProvider
only in config
block, since it is a provider. However, you can have multiple config
sections in your app. That means that if you have several files, each one of them may define another portion of routes inside config
section of it's own.
HTML
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://code.angularjs.org/1.2.14/angular.js"></script>
<script src="http://code.angularjs.org/1.2.14/angular-route.js"></script>
<script src="script.js"></script>
<script src="another_script.js"></script>
</head>
<body>
<a href="#/route1">Route 1</a>
<a href="#/route2">Route 2</a>
<div ng-view></div>
</body>
</html>
script.js
angular.module('app', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/route1', {
template: '<h1>Route 1</h1>'
}).
otherwise({
redirectTo: '/route1'
})
}]);
another_script.js
angular.module('app').
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/route2', {
template: '<h1>Route 2</h1>'
})
}]);
Plunker: http://plnkr.co/edit/ZHNTAiW6VsZmQXjSJH2f?p=preview
If you need to add routes dynamically at runtime after application is bootstrapped, you may probably be interested in non-standard solutions like mentioned here