Pro AngularJS, Chapter 18
by js_test
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<body ng-app="exampleApp" ng-controller="defaultCtrl">
<div class="well">
<div class="btn-group" tri-button counter="data.totalClicks" source="data.cities">
<button class="btn btn-default" ng-repeat="city in data.cities">{{city}}</button>
</div>
<h5>Total Clicks: {{data.totalClicks}}</h5>
</div>
</body>
JavaScript
angular.module("exampleApp", ["customDirectives", "customServices"])
.controller("defaultCtrl", function ($scope, logService) {
$scope.data = {
cities: ["London", "New York", "Paris"],
totalClicks: 0
};
$scope.$watch('data.totalClicks', function (newVal) {
logService.log("Total click count: " + newVal);
});
});
angular.module("customServices", [])
.factory("logService", function () {
var messageCount = 0;
return {
log: function (msg) {
console.log("(LOG + " + messageCount++ + ") " + msg);
}
};
})
angular.module("customDirectives", [])
.directive("triButton", function () {
return {
scope: {
counter: "=counter"
},
link: function (scope, element, attrs) {
element.on("click", function (event) {
console.log("Button click: " + event.target.innerText);
scope.$apply(function () {
scope.counter++;
});
});
}
}
});