In my previous post, I created a project for a simple web application using Spring Boot and Maven. I want to take it further and add AngularJS support to the setup.
I am an avid birder so I am going to develop a Bird Log app to log my bird sightings. Recently, I was introduced to AngularJS and have become a big fan of this framework. I am going to develop a Single Page Application (SPA) using AngularJS and Twitter Bootstrap Framework for HTML and CSS.
Why AngularJS?
- AngularJS supports Dependency Injection, thus enabling IoC (Inversion of Control). DI simplifies the development and dependency management.
- AngularJS enables writing testable code. Support for DI makes it easier to write unit tests and end-to-end (e2e) tests for the code.
- AngularJS supports [two way data binding](http://docs.angularjs.org/guide/databinding where data between model and view is automatically synchronized. For example, if model field name is bound to a textfield, changing the value of textfield is immediately reflected in the model and vice-a-versa. For me, this was a game changer that simplifies the code immensely.
- AngularJS is modular. Apart from Dependency Injection, AngularJS is broken down into components like
Controllers
,Services
,Directives
,Filters
andViews
. - AngularJS simplifies management of state through dependency injection and inheritance of
$scope
.
Before we begin
This post assumes that you are familiar with the AngularJS framework. This post explains how to configure and use AngularJS within Spring and Maven project. If you are new to AngularJS, please take a look at AngularJS Guides or many other excellent tutorials online.
Setting up AngularJS in Spring Boot Application
In this example, Maven is used to manage dependencies for Java components. I plan to use Bower, the package manager for the web, to simplify management AngularJS and other related Javascript package dependencies.
Note: Use of Bower is optional. If you are not familiar with Bower or don’t want to use Bower, please configure the required packages (AngularJS and Bootstrap for now) manually.
- Enable BOWER support for dependency management.
cd <project dir>
Create
.bowerrc
file and add the following lines{ "directory": "src/main/resources/static/bower_components" }
Note: This step ensures that Bower copies managed dependencies to the correct location.
-
Initialize Bower
bower init [?] name: sample-app [?] version: 1.0.0 [?] description: AngularJS Starter App [?] main file: [?] what types of modules does this package expose? [?] keywords: AngularJS, Spring Boot, Maven [?] authors: Rajan Desai <rajan11@hotmail.com> [?] license: MIT [?] homepage: [?] ssset currently installed components as dependencies? Yes [?] add commonly ignored files to ignore list? Yes [?] would you like to mark this package as private which prevents it from being accidentally published to the registry? Yes { name: 'starter-app-ng', version: '0.0.1', authors: [ 'Rajan Desai <rajan11@hotmail.com>' ], description: 'AngularJS Starter App', keywords: [ 'AngularJS', 'Spring Boot', 'Maven' ], license: 'MIT', private: true, ignore: [ '**/.*', 'node_modules', 'bower_components', 'src/main/resources/static/bower_components', 'test', 'tests' ] } [?] Looks good? (Y/n)
Press
Y
to createbower.json
file with the above configuration in your root project directory. AllBower
commands will be executed from the root project folder going forward. -
Add
AngularJS
supportbower install angular --save
- Above command downloads the latest stable version (1.2.14 at the time) to
<project folder>/src/main/resources/static/bower_components/angular
folder. -
--save
option adds dependencies to thebower.json
file. The following lines will be added to thebower.json
file"dependencies": { "angular": "~1.2.14" }
- Add other
AngularJS
related packagesbower install angular-route --save bower install angular-resource --save bower install angular-cookies --save bower install angular-sanitize --save
- Above command downloads the latest stable version (1.2.14 at the time) to
- Add
Bootstrap
support`bower install bootstrap --save`
At the time of writing this post, the above command installs
Bootstrap 1.9.0
to<project folder>/src/main/resources/static/bower_components/bootstrap
folderNote: Bower manages dependencies for you. Since Bootstrap requires
JQuery
, Bower will automatically download the requiredJQuery
package for you. At this time, Bower installedJQuery 2.1.0
package in<project folder>/src/main/resources/static/bower_components/jquery
folder
Develop Web Application using AngularJS
Now that I have my Spring Boot Application
(see Part 1) setup with AngularJS
support, I can start developing my Bird Log application.
- Modify
index.html
to include angular support- Define an angular app using
ng-app
directive. This directive is used to auto-bootstrap an Angular app. Only 1 ng-app can be auto-bootstrapped in one HTML document. This element defines the root scope for the application.<body ng-app="StarterApp">
Where,
- Placing ng-app on the body tag tells the angular framework that our application is scoped to the entire page. Typically this directive is placed near the root element on the page, for example, on the or tags.
- StarterApp is a name of the app that we are creating. We will define an angular module with this exact name below to tie it all together.
- Define an angular app using
- Define
StarterApp
module that is loaded by AngularJS as the application is bootstrapped. This acts like amain
method in Java application.- Create
app
andapp/js
directories in<project folder>/src/main/resources/static/
folder.- Create
app/main.js
file that defines theStarterApp
module.var starterApp = angular.module("StarterApp", ["ngRoute"]);
NOTES:
- make sure that the name of the module is exactly the same as the one specified in ng-app directive above.
- second parameter is a list of dependencies. AngularJS injects specified dependencies at runtime. In this case, our App needs ngRoute module that defines the $routeProvider.
- Create
- Define routes in the config function
starterApp.config(function($routeProvider) { $routeProvider.when('/', { templateUrl: 'views/home.html', controller: 'HomeCtrl' }) .otherwise({redirectTo : '/'}); });
NOTES:
- AngularJS calls the
config
function during bootstrap process. $routeProvider
is injected by the AngularJS framework$routeProvider
maps app urls to the view (templateUrl
) andcontroller
otherwise
option defines thedefault handler
for unmapped URLs. In this app, user is simply redirected to the main view.
- AngularJS calls the
- Create
- Implement
Home View
- Create
views
directory in<project folder>/src/main/resources/static/app
folder- Create
home.html
file to define the view template
- Create
Home View
- Create
- Implement
HomeCtrl
used in the previous step- Create
app/controllers/homeCtrl.js
. I am going to create a new module calledStarterApp.home
to handleHome
functionality. ControllerHomeCtrl
will defined in this module.angular.module('starterApp.home', []) .controller('HomeCtrl', function() { });
NOTES:
starterApp.home
is the name of the module and [] defines an empty list of dependencies (for now).
- Inject
starterApp.home
module in the main Angular app- modify main.js file
var starterApp = angular.module(“StarterApp”, [“ngRoute”, “starterApp.home”]);
NOTE:
- I now have added
starterApp.home
module as a dependency to the mainstarterApp. This will make the
HomeCtrl defined instarterApp.home
module available in the main app. - Modify
index.html
to define a place for ourmain
view usingng-view
directive. This directive work with theng-route
directive to include the view template into the main application layout. Everytime current route changes, corresponding view template is included in the view. This directive creates a new child scope.<div class="container" ng-view></div>
- modify main.js file
- Load required CSS and Javascript files by modifying
index.html
<!-- APP: js --> <script src="app/js/main.js"></script> <script src="app/js/controllers/homeCtrl.js"></script> <script src="app/js/controllers/ebirdCtrl.js"></script> <script src="app/js/controllers/aboutCtrl.js"></script> <script src="app/js/controllers/googleApisCtrl.js"></script> <!-- end APP -->
- At this point, the
index.html
should look like this:<html> <head> <title>AngularJS Starter App</title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css"> </head> <body ng-app="StarterApp"> <h2>Hello World!</h2> <!-- Add your site or application content here --> <div class="container" ng-view></div> <!-- LIBS: js --> <script src="bower_components/jquery/dist/jquery.js"></script> <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-route/angular-route.js"></script> <!-- end LIBS --> <!-- APP: js --> <script src="app/js/main.js"></script> <script src="app/js/controllers/homeCtrl.js"></script> <!-- end APP --> </body> </html>
- Run app and browse to http://localhost:8080, you should see both
Hello World!
andHome View
.
- Create
###Sum it up
At this point, I have a basic working AngularJS application. The application doesn’t do much yet, but I’ll add more details to it soon. In the next post, I’ll beautify the app using Bootstrap framework.
The best post on the field I ever read.
Very accurate and well documented.
Thank you Ranjandesai. God Bless you.
Any chance to send me source code of the finished work ?
Best regards,
Robert
Hi Rajandesai.
I’m on part 2. My code don’t work.
With localhost:8080 I can see only the index.html page but without the content of my template home.html page.
Can you please send me urgently your working code in order to compare ?
Best regards,
Robert.
main.js :
var starterApp = angular.module(“StarterApp”, [“ngRoute”, “starterApp.home”]);
starterApp.config(function($routeProvider) {
$routeProvider.when(‘/’, {
templateUrl: ‘views/home.html’,
controller: ‘HomeCtrl’
})
.otherwise({redirectTo : ‘/’});
});
homeCtrl.js :
angular.module(‘starterApp.home’, [])
.controller(‘HomeCtrl’, function() {
});
index.html :
AngularJS Starter App
Hello World!!!!!!!!!!
<!-- LIBS: js -->
<!-- end LIBS -->
<!-- APP: js -->
<!-- end APP -->
home.html :
Hi !!!! You are at Home
bower.json :
{
“name”: “sample-app”,
“version”: “1.0.0”,
“authors”: [
“Robert Togbe ”
],
“description”: “Angularjs starter app”,
“keywords”: [
“Angularjs”,
“Spring”,
“Boot”,
“Maven”
],
“license”: “MIT”,
“private”: true,
“ignore”: [
“**/.*”,
“node_modules”,
“bower_components”,
“src/main/resources/static/bower_components”,
“test”,
“tests”
],
“dependencies”: {
“angular”: “~1.2.16”,
“angular-route”: “~1.2.16”,
“angular-resource”: “~1.2.16”,
“angular-cookies”: “~1.2.16”,
“angular-sanitize”: “~1.2.16”,
“bootstrap”: “~3.1.1”
}
}
Get the code here: http://rajandesai.com/blog/wp-content/uploads/2014/03/code.zip