Last active
December 21, 2015 05:58
-
-
Save rctay/6260428 to your computer and use it in GitHub Desktop.
simple vote counting/tallying with angular http://plnkr.co/edit/gist:6260428
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html ng-app> | |
<head> | |
<meta charset='utf-8'> | |
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> | |
<script src="script.js"></script> | |
</head> | |
<body> | |
<div ng-controller="Controller"> | |
<p ng-repeat="name in candidates"> | |
{{name}}: {{counts[$index] || 0}} | |
<button ng-click="plusOne($index, name)">+1</button> | |
</p> | |
<p> | |
void: {{counts['void'] || 0}} | |
<button ng-click="plusOne('void', 'void')">+1</button> | |
</p> | |
<p> | |
Total: {{total}} | |
</p> | |
<p> | |
强者(champion) = {{max_candidate}} with {{max_percentage()}}% of votes | |
</p> | |
</div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Controller($window, $scope){ | |
$scope.candidates = [ | |
"Ah Kow", | |
"Ah Teck" | |
]; | |
$scope.counts = {}; | |
$scope.total = 0; | |
$scope.max_candidate = ""; | |
$scope.max_count = 0; | |
$scope.plusOne = function(x, label) { | |
if (!$scope.counts.hasOwnProperty(x)) | |
$scope.counts[x] = 0; | |
var count = ++$scope.counts[x]; | |
if (count > $scope.max_count) { | |
$scope.max_count = count; | |
$scope.max_candidate = label; | |
} | |
$scope.total++; | |
} | |
$scope.max_percentage = function() { | |
if ($scope.max_count === 0 || $scope.total === 0) | |
return 0; | |
var frac = $scope.max_count / $scope.total * 100; | |
return Math.round(frac * 10) / 10; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment