我有一个服装指令来设置%的东西,例如:
– 快乐:[90]
– 悲伤:[10]
– 快乐:[90]
– 悲伤:[10]
所以它只允许1到100.所以我不想允许任何字符等.我知道我可以使用ng-pattern等..但我不希望他们甚至添加一个字符所以我必须这样做.
它的工作原理,但我遇到的问题是空间不会触发$解析器,是否有一个解决方法用于触发空间?
app.directive('numericOnly',function(){ return { require: 'ngModel',link: function(scope,element,attrs,modelCtrl) { modelCtrl.$parsers.push(function (inputValue) { //Remove all non numeric values var transformedInput = inputValue.replace(/\D/g,''); //Remove all spaces transformedInput = transformedInput.replace(/\s/g,""); //Remove any leading zero if(transformedInput.substring(0,1) === '0') { console.log('is zero'); if(transformedInput.length === 1) { transformedInput = ''; } else { transformedInput = transformedInput.substring(1,transformedInput.length); } } //Make sure it is not over 100 var numberCopy = parseInt(transformedInput); if(!isNaN(numberCopy)){ if(numberCopy > 100) { console.log('bigger than 100'); numberCopy = 100; transformedInput = String(numberCopy); } } //If changes done,then update modelCtrl if (transformedInput!=inputValue) { modelCtrl.$setViewValue(transformedInput); modelCtrl.$render(); } //Return return transformedInput; }); } }; });