Single Page Applications with Backbone.js and AngularJS

Hash Tags
The hash tag (#) is used when linking to anchors within a current web page. The use of anchors allows the user to navigate to different parts of the page without going to a new URL. For example,

navigates to the part of the page with anchor

Both Backbone and AngularJS make use of # for routing application URLs in single page applications. In both cases, all links in the application should target “#/action” or “#action”. e.g. http://example.com/#/user. When the user clicks on different links within the application, instead of going to a different place on the page, different portions of the JavaScript in the code get executed.

Backbone.js Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<!DOCTYPE html>
<html>
<head>
<title>Backbone Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
</head>
<body>

<ul>
<li><a href="#">Home</a></li>
<li><a href="#/about">About</a></li>
<li><a href="#/contact">Contact</a></li>
<li><a href="#/redirect">Redirect</a></li>
</ul>

<div class="content"></div>
 
<script type="text/template" id="home-template">
<p><%= value %></p>
</script>

<script type="text/template" id="about-template">
<p><%= value %></p>
</script>

<script type="text/template" id="contact-template">
<p><%= value %></p>
</script>

<script type="text/template" id="redirect-template">
<p>This illustrates the use of backbone's router.navigate('nav', {trigger:true})
which automatically redirects to other locations in the application.  For example,
after saving, updating or deleting data from a database, you might might want to
show some kind of 'success' page.</p>
</script>


<script type="text/javascript">

var Router = Backbone.Router.extend({
   routes: {
    "": "homeview", // url:event that fires
    "about": "aboutview",
    "contact": "contactview",
    "redirect":"redirectview"
  },

// the 'home' view
homeview: function() {
    var content = "welcome to the home page";
    var template = _.template($('#home-template').html(), {value: content});
    $(".content").html(template);
    var HomeView = Backbone.View.extend({
    el: '.content',  
    initialize:function(){
        this.render();
    },
    render: function () {
        this.$el.html(template);
    }
});
var hmview = new HomeView();
},

// the 'about' view
aboutview: function() {
    var content = "welcome to the about page";
    var template = _.template($('#about-template').html(), {value: content});
    $(".content").html(template);
    var AboutView = Backbone.View.extend({
    el: '.content',  
    initialize:function(){
        this.render();
    },
    render: function () {
        this.$el.html(template);
    }
});
var abtview = new AboutView();
},

// the 'contact us' view
contactview: function() {
    var content = "welcome to the contact us page";
    var template = _.template($('#contact-template').html(), {value: content});
    $(".content").html(template);
    var ContactView = Backbone.View.extend({
    el: '.content',    
    initialize:function(){
        this.render();
    },
    render: function () {
        this.$el.html(template);
    }
});
var conview = new ContactView();
},

// demonstrates the automatic redirect functionality
redirectview: function() {
    alert('On closure this we will automatically redirect to another location in the application.');
    router.navigate('redirect', {trigger:true});
    var template = _.template($('#redirect-template').html(), {});
    $(".content").html(template);
    var RedirectView = Backbone.View.extend({
    el: '.content',  
    initialize:function(){
        this.render();
    },
    render: function () {
        this.$el.html(template);
    }
});
var rdview = new RedirectView();
}
});
var router = new Router;

/*
This is an alternative syntax  to the above that uses JQuery's "on" method
 
router.on('route:homeview', function() {
   ...
 }
*/

// Start Backbone history
Backbone.history.start();
</script>

</body>
</html>

See the live demo here

The equivalent of the above using AngularJS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-route.js"></script>
</head>
<body>

<div ng-app="myApp">

<ul>
<li><a href="#">Home</a></li>
<li><a href="#/about">About</a></li>
<li><a href="#/contact">Contact</a></li>
<li><a href="#/redirect">Redirect</a></li>
</ul>

<div ng-view></div>

</div>

<script>
// create a new module
// also include ngRoute for all our routing needs
   
var myApp = angular.module('myApp', ['ngRoute']);

// configure the routes
   
myApp.config(function($routeProvider) {
/*
AngularJS's $routeProvider has a very basic api for defining application's routes.
$routeProvider.when() is used to match a url pattern to a view while
$routeProvider.otherwise() is used to render a view when there is no
match to a url pattern.
*/


$routeProvider

// route for the home page
  .when('/', {
         templateUrl : 'pages/home.html',
         controller  : 'homeController'
        })

// route for the about page
.when('/about', {
                 templateUrl : 'pages/about.html',
                 controller  : 'aboutController'
              })

// route for the contact page
.when('/contact', {
                   templateUrl : 'pages/contact.html',
                   controller  : 'contactController',
                })

// route for the redirect page
.when('/redirect', {
                    templateUrl : 'pages/redirect.html',
                    controller  : 'redirectController',
                    // automatically redirect
                    redirectTo: '/redirect'
                });
    });
   
// create the controller and inject Angular's $scope
myApp.controller('homeController', function($scope) {
// create a message to display in the view
$scope.message = 'welcome to the home page';
    });

myApp.controller('aboutController', function($scope) {
    $scope.message = 'welcome to the about page.';
    });

myApp.controller('contactController', function($scope) {
    $scope.message = 'welcome to the contact us page.';
    });

myApp.controller('redirectController', function($scope) {
    $scope.message = 'This illustrates the use of AngularJS\'s  redirectTo method which automatically redirects to other locations in the application.  For example, after saving, updating or deleting data from a database, you might might want to show some kind of \'success\' page.';
    alert('On closure this we will automatically redirect to another location in the application.');
    });

</script>

</body>
</html>

Directory Structure

index.html
pages
|_ home.html
|_ about.html
|_ contact.html
|_ redirct.html

home.html/about.html/contact.html/redirect.html

1
2
3
<div>
<p>{{ message }}</p>
</div>

See the live demo here

Leave a Reply