Input to an array
by jacobwsmith
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div ng-controller="myCtrl">
<form name="form">
List of Numbers:<br>
<nl-array-to-number ng-model="numberArr"></nl-array-to-number>
<br> {{numberArr}}
</form>
</div>
CSS
html,
body {
margin: 10px;
}
input {
margin: 5px;
}
JavaScript
angular.module('app', []).controller('myCtrl', function($scope) {
$scope.numberArr = [123, 321, 999];
})
.directive('nlArrayToNumber', function() {
return {
restrict: 'E',
scope: {
ngModel: '=',
},
// TODO: this probably could be a controller
link: function(scope, elem, attrs) {
// Set the textValue
if (scope.ngModel) {
scope.textValue = scope.ngModel.toString();
}
// Watch and set the textValue
scope.$watch('ngModel', function(newValue, oldValue) {
if (newValue !== oldValue) {
console.log(newValue);
console.log(newValue.toString());
scope.textValue = newValue.toString();
console.log('textValue' + scope.textValue);
}
}, true);
// Keydown
scope.keydown = function(event) {
console.log('=== keydown ===');
if ([8, 9, 13, 17, 27, 37, 38, 39, 40, 224, 188].indexOf(event.keyCode) > -1) { // delete(8), tab(9), return(13), escape(27), ctrl(17), command(224 firefox), comma(188), arrow keys(37-40)
return true;
} else if ((event.metaKey || event.ctrlKey) && [65, 67, 86].indexOf(event.keyCode) > -1) {
// Select all, Copy, Paste Keys
return true;
} else if ((!event.shiftKey) && ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105))) {
// Numbers Only
return true;
} else {
event.preventDefault();
return false;
}
}
// Change
scope.blur = function(event) {
console.log('=== change ===');
var i = 0,
inputArray = [],
inputText = scope.textValue, // <-- setting this to the scoped textValue
len = 0;
// Remove Any non-numeric characters and replace with pipe
inputText =...