Angular 1.2.16 route
http://angularjs.org/
by Sajeetharan Sinnathurai
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script src="https://code.angularjs.org/1.2.16/angular-route.js"></script>
<body ng-app="sampleApp">
<h1>AngularJS : Controllers, Services, Directives</h1>
<div ng-controller="bookctrl">
<ul class="nav">
<li><a href="#home"> Home </a></li>
<li><a href="#addHorror"> Add Horror Book </a></li>
<li><a href="#addRomCom"> Add RomCom Book </a></li>
</ul>
<ul>
<li ng-repeat="book in books">
<h2>{{book.title}}</h2>
<h3>- by {{book.author}}</h3></li>
</ul>
</div>
<div ng-view></div>
<script type="text/ng-template" id="add_book.html">
<article style="border:dotted 1px black; width:200px; margin-left:50px;">
<h2>{{message}}</h2>
<input text ng-model="book.title" />
<input text ng-model="book.author" />
<add-book-button bookobjattr="book"></add-book-button>
</article>
</script>
</body>
JavaScript
var sampleApp = angular.module('sampleApp', ['ngRoute']);
sampleApp.config(["$routeProvider",
function ($routeProvider) {
$routeProvider.
when("/addRomCom", {
templateUrl: "add_book.html",
controller: "romcomctrl"
}).
when("/addHorror", {
templateUrl: "add_book.html",
controller: "horrorctrl"
}).
otherwise({
redirectTo: "/"
});
}
]);
//defines service for your app
sampleApp.service("bookservice", ["$rootScope", function ($rootScope) {
var service = {
books: [{
title: "Magician",
author: "Raymond E. Feist"
}, {
title: "The Hobbit",
author: "J.R.R Tolkien"
}],
addBook: function (book) {
service.books.push(book);
$rootScope.$broadcast("books.update");
}
}
return service;
}]);
//defines controller for your app
sampleApp.controller("bookctrl", ["$scope", "bookservice",
function ($scope, bookservice) {
$scope.books = bookservice.books;
$scope.$on("books.update", function (event) {
$scope.books = bookservice.books;
});
}
]);
sampleApp.controller("horrorctrl", function ($scope) {
$scope.message = "This will add horror book";
$scope.book = {
title: "",
author: ""
};
});
sampleApp.controller("romcomctrl", function ($scope) {
$scope.message = "This will add romcom book";
$scope.book = {
title: "",
author: ""
};
});
//defines directive for your app
sampleApp.directive("addBookButton", ["bookservice", function (bookservice) {
return {
restrict: "EA",
transclude: true,
scope: {
book: "=bookobjatt"
},
template: "<button ng-click=\"addbook()\"> Add Book </button>",
link: function (scope, element, attrs) {
debugger;
scope.addbook = function () {
bookservice.addBook(scope.book);
}
}
}
}]);