My $parser
function restricts the number of characters a user can enter:
var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11;
function fromUser(inputText) {
if (inputText) {
if (inputText.length > maxLength) {
var limitedText = inputText.substr(0, maxLength);
ngModel.$setViewValue(limitedText);
ngModel.$render();
return limitedText;
}
}
return inputText;
}
ngModel.$parsers.push(fromUser);
I am facing an issue where I need to apply this directive to an input element with
ng-model-options="{updateOn: 'blur'}"
. Currently, the $parser
runs only after the user clicks out of the input field. Is there a way to make it execute as the user types?
(function (angular) {
"use strict";
angular.module('app', [])
.controller("MainController", function($scope) {
$scope.name = "Boom !";
$scope.name2 = "asdf";
}).directive('limitCharacters', limitCharactersDirective);
function limitCharactersDirective() {
return {
restrict: "A",
require: 'ngModel',
link: linkFn
};
function linkFn(scope, elem, attrs, ngModel) {
var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11;
function fromUser(inputText) {
if(inputText) {
if (inputText.length > maxLength) {
var limitedText = inputText.substr(0, maxLength);
ngModel.$setViewValue(limitedText);
ngModel.$render();
return limitedText;
}
}
return inputText;
}
ngModel.$parsers.push(fromUser);
}
}
})(angular);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<div ng-app="app">
without ng-model-options: <input type="text" ng-model="name" limit-characters limit="7" />
<br>
with ng-model-options <input type="text" ng-model="name2" ng-model-options="{updateOn: 'blur'}" limit-characters limit="7" />
</div>