JSFiddle - React, Tailwind, and code Playground
HTML
<div ng-app="app" ng-controller="MainController">
without ng-model-options: <input type="text" ng-model="name" limit-characters limit="7" />
<p>
model value: {{name}}
</p>
<br>
with ng-model-options <input type="text" ng-model="name2" ng-model-options="{updateOn: 'blur'}" limit-characters limit="7" />
<p>
model value: {{name2}}
</p>
</div>
JavaScript
(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;
angular.element(elem).on("keypress", function(e) {
if (this.value.length == maxLength) e.preventDefault();
});
}
}
})(angular);