I neeed an input field where I can enter only the values 1,2 or 3 so i\'m trying to build a directive which prevents all changes to the model if it doesn\'t match these valu
You could always listen to the keypress event and prevent the character from making it through. Here is a plunker
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.validValues = ['a','1','2'];
});
app.directive('myValidator', function ($parse) {
return {
scope: {
validValues: '=validValues'
},
link: function (scope, elm, attrs) {
elm.bind('keypress', function(e){
var char = String.fromCharCode(e.which||e.charCode||e.keyCode), matches = [];
angular.forEach(scope.validValues, function(value, key){
if(char === value) matches.push(char);
}, matches);
if(matches.length == 0){
e.preventDefault();
return false;
}
});
}
}
});