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'> 
    
<head> 
    <script src="scripts/Angularjs/angular.js" ></script> 
    <script src="scripts/Angularjs/angular-route.min.js"></script>
    <script src="/scripts/Angularjs/_app.js"></script>
</head>
    <body>
        <div id="nav-bar">
            <a href="#/">Home</a> | <a href="#/second">Second</a>
        </div>
        <div class='container'>
            <div ng-view></div>
        </div>
        
    </body>

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

<h1>{{pageName}}</h1>

Here is scripts/second.html

<h1>{{pageName}}</h1>

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

var myApp = angular.module('myApp', ['ngRoute']); 
 
//setting up a SPA
myApp.config (function($routeProvider)  {
    
    
    $routeProvider
    .when('/',{
        templateUrl: 'pages/main.html',
        controller: 'mainController'
    })
    
    .when('/second',{
        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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s