Adding a New Blog Controller
Categories: Angular Angular JS
Adding a New Blog Controller
Next we will set up the controllers for our new blog application. The following code defines the blogControllers module and the BlogCtrl controller for that module. We will define more controllers on the blogControllers module as we work on the blog application. For now, the controllers.js file is relatively small:
/* chapter5/controllers.js */
'use strict';
/* Controllers */
var blogControllers =
angular.module('blogControllers', []);
blogControllers.controller('BlogCtrl', ['$scope',
function BlogCtrl($scope) {
$scope.blogArticle =
"This is a blog post about AngularJS.
We will cover how to build a blog and how to add
comments to the blog post.";
}]);
Next is the code for the app.js file that starts the booting process for the blog application. This is where we define the route for the main page of the blog. As you can see, we define ngRoute and blogControllers as dependencies of the application at startup time, using inline array annotations. The two dependencies are injected into the application using DI and are available throughout the application when we need them. Any controllers attached to the blogControllers module are accessible to the blogApp module (the AngularJS application):
/* chapter5/app.js */
'use strict';
/* App Module */
var blogApp = angular.module('blogApp', [
'ngRoute',
'blogControllers'
]);
blogApp.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/main.html',
controller: 'BlogCtrl'
});
$locationProvider.html5Mode(false).hashPrefix('!');
}]);
The routes are defined in the application configuration block. For now, we will only define the main page of the blog. We define BlogCtrl as the controller and 'partials/main.html' as the template used for the main route. We will add more routes as we need them.