Angular: Test of Controllers, Directives and Services
http://angularjs.org/
by Pixic
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<div ng-app="myApp">
<div ng-controller="MainCtrl as mainCtrl">
<h1>Test of Controllers, Directives and Services</h1>
<button ng-click="mainCtrl.open('first')">
Open first
</button>
<button ng-click="mainCtrl.open('second')">
Open second
</button>
<div ng-switch on="mainCtrl.tab">
<div ng-switch-when="first">
<div ng-controller="SubCtrl as ctrl">
<h3>First tab</h3>
<ul>
<li ng-repeat="item in ctrl.list()">
<span ng-bind="item.label"></span>
</li>
</ul>
<button ng-click="ctrl.add()">
Add more items
</button>
</div>
</div>
<div ng-switch-when="second">
<div ng-controller="SubCtrl as ctrl">
<h3>Second tab</h3>
<ul>
<li ng-repeat="item in ctrl.list()">
<span ng-bind="item.label"></span>
</li>
</ul>
<button ng-click="ctrl.add()">
Add more items
</button>
</div>
</div>
</div>
</div>
</div>
JavaScript
var app = angular.module('myApp', []);
app.controller('MainCtrl', [function() {
var self = this;
self.tab = 'first';
self.open = function(tab) {
self.tab = tab;
}
}]);
app.controller('SubCtrl', ['ItemService', function(ItemService) {
var self = this;
self.list = function() {
return ItemService.list();
}
self.add = function() {
ItemService.add({
id: self.list().length + 1,
label: 'Item' + self.list().length
});
}
}]);
app.factory('ItemService', [function() {
var items = [
{id: 1, label: 'Item 0'},
{id: 1, label: 'Item 1'}
];
return {
list: function() {
return items;
},
add: function(item) {
items.push(item);
}
};
}]);