Book-AngularJS- Up and Running - Chapter-5
All About AngularJS Services
by kibria
HTML
<body ng-app='notesApp' ng-controller="MainCtrl as mainCtrl">
<h1>Hello Controllers!</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>
</body>
JavaScript
angular.module('notesApp', [])
.controller('MainCtrl', [function () {
var self = this;
self.tab = 'first';
self.open = function (tab) {
self.tab = tab;
};
}])
.controller('SubCtrl', [function () {
var self = this;
self.list = [{
id: 1,
label: 'Item 0'
}, {
id: 2,
label: 'Item 1'
}];
self.add = function () {
self.list.push({
id: self.list.length + 1,
label: 'Item ' + self.list.length
});
};
}]);