我需要一个输入字段,我只能在其中输入值 1,2 或 3,因此我正在尝试构建一个指令,如果它与这些值不匹配,它会阻止对模型的所有更改。
例如,值为 1,我将其更改为 5,它应该仍然是 1。
我整理了一个小小提琴http://jsfiddle.net/kannix/Q5YKE/但使用 $parsers 很可能是错误的。
app.directive('myvalidator', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var validValues = [1,2,3];
ctrl.$parsers.push(function (value) {
if (validValues.indexOf(value) === -1){
//what to do here? should refuse wrong value and leave the old one
}
});
}
}
})