Setting up a simple SPA with Angularjs

An SPA is a ‘Single Page Application’.

Setting up Angular routing and templates so you can have a SPA can be fairly simple. Here is a very basic example to get started.

Here is my index.html file. It has a div with the ng-view attribute, which is where html of pages will be injected.

<html ng-app='myApp'> 
    <script src="scripts/Angularjs/angular.js" ></script> 
    <script src="scripts/Angularjs/angular-route.min.js"></script>
    <script src="/scripts/Angularjs/_app.js"></script>
        <div id="nav-bar">
            <a href="#/">Home</a> | <a href="#/second">Second</a>
        <div class='container'>
            <div ng-view></div>

I have folder called ‘scripts’ that contains 2 more html files.
Here is scripts/main.html:


Here is scripts/second.html


Here is my _app.js file which sets up routing:

var myApp = angular.module('myApp', ['ngRoute']); 
//setting up a SPA
myApp.config (function($routeProvider)  {
        templateUrl: 'pages/main.html',
        controller: 'mainController'
        templateUrl: 'pages/second.html',
        controller: 'secondController'

myApp.controller('mainController',['$scope', function($scope){
     $scope.pageName = 'Main';

myApp.controller('secondController',['$scope', function($scope){

    $scope.pageName = 'Second';

Once setup, this will initially load the index.html, and since the url hit will be http://%5Bserver%5D/index.html, it will load the first route (‘/’) as a default. The screen will say ‘Main’ which is being pulled from the ‘mainController’ code and put into the {{pageName}} tag in main.html, then that is injected into the ng-view of index.html.
When you click the ‘Second’ link on the index.html page, it will get the display the ‘second.html’ view in the ng-view, and the screen will show ‘Second’ as it is pulled from the ‘secondController’ and loaded into the {{pageName}} tag in second.html and injected into ng-view of index.html.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s