Skip to content

Instantly share code, notes, and snippets.

@menacestudio
Created March 13, 2015 21:35
Show Gist options
  • Save menacestudio/e4d0a1ad2c3dba4be69c to your computer and use it in GitHub Desktop.
Save menacestudio/e4d0a1ad2c3dba4be69c to your computer and use it in GitHub Desktop.
An AngularJS directive for handling score input.
scoreInput.$inject = [];
function scoreInput() {
return <ng.IDirective>{
restrict: 'E',
replace: true,
scope: {
model: '=ngModel',
isRequired: '=',
isReadonly: '=',
scaleMax: '=',
increment: '=',
placeHolder: '@placeHolder',
onDecrement: '&',
onIncrement: '&'
},
transclude: true,
template:
'<div class="input-group col-md-11 col-xs-11">' +
' <span class="input-group-btn">' +
' <button data-ng-click="decrementScore($event)" type="button" class="btn btn-orange"><span class="glyphicon glyphicon-minus"></span></button>' +
' </span>' +
' <input type="text" data-ng-required="isRequired" data-ng-readonly="isReadonly" ng-model="model" class="form-control" placeholder="{{::placeHolder}}" data-ng-keydown="onKeyDown($event)" />' +
' <span class="input-group-btn">' +
' <button data-ng-click="incrementScore($event)" type="button" class="btn btn-orange"><span class="glyphicon glyphicon-plus"></span></button>' +
' </span>' +
'</div>',
link: link
}
function link($scope, $element, $attrs) {
var min = 0,
max = $scope.scaleMax,
increment = $scope.increment;
// Decrement score
$scope.decrementScore = function ($event) {
if ($event) $event.preventDefault();
var scoreNum = $scope.model || min;
if (scoreNum > min) {
$scope.model = (scoreNum - increment);
}
$scope.onDecrement($scope.model);
};
// Increment score
$scope.incrementScore = function ($event) {
if ($event) $event.preventDefault();
var scoreNum = $scope.model || min;
console.log(scoreNum, max, increment);
if (scoreNum < max) {
$scope.model = scoreNum + increment;
}
$scope.onIncrement($scope.model);
};
$scope.onKeyDown = function ($event) {
var key = $event.which || event.keyCode;
console.log(key);
// Allow numbers and backspace
if ((key < 48 || key > 57) && key !== 8) {
$event.preventDefault();
return;
}
// Check and project model value after keypress
var modelValue = $scope.model || 0,
keyValue = parseInt($event.key) || 0;
if ((parseInt(modelValue + '' + keyValue) > max) && key !== 8) $event.preventDefault();
}
}
}
angular.module('app').directive('scoreInput', scoreInput);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment