I have this $parser
which limits the number of characters that user has entered:
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 want to use this directive on an input element which has ng-model-options="{updateOn: 'blur'}"
, but there is a problem that the whole $parser
thing gets executed after user loses the focus of input element, I want it to get executed as user types into the input field.
(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>