<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.2.16" data-semver="1.2.16" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="CountExample">
<div ng-controller="Controller">
<div count="reviewCount" count-class="count-this">
<div class="count-this">Review One</div>
<div class="count-this">Review Two</div>
<div class="dont-count-this">Something else</div>
<div class="count-this">Review Three</div>
</div>
<p>
Count: {{reviewCount}}
</p>
</div>
</body>
</html>
angular.module('CountExample', [])
.controller('Controller', ['$scope', function($scope) {
$scope.reviewCount = 0;
}])
/*
Counts all the children of the element on which the directive is applied which
have the class specified by the 'count-class' attribute.
The resulting count is bound to the controller scope variable specified by
the 'count' attribute.
*/
.directive('count', function() {
return {
restrict: 'A',
scope: {
countClass: '@',
count: '='
},
link: function(scope, element, attrs) {
var matching = element[0].querySelectorAll('.'+scope.countClass);
scope.count = matching ? matching.length : 0;
}
};
});
Angular Count Directive
Directive for counting child elements with a particular class.