// declare a module var myApp = this.angular.module('myApp', []); // declare a controller myApp.controller('InputCtrl', function ($scope) { }); myApp.directive('inputMaxLengthNumber', function() { return { require: 'ngModel', restrict: 'A', link: function (scope, element, attrs, ngModelCtrl) { function fromUser(text) { var maxlength = Number(attrs.maxlength); if (String(text).length > maxlength) { ngModelCtrl.$setViewValue(ngModelCtrl.$modelValue); ngModelCtrl.$render(); return ngModelCtrl.$modelValue; } return text; } ngModelCtrl.$parsers.push(fromUser); } }; })
<!-- stitch this with the module declare in Javascript --> <body ng-app="myApp"> <div ng-controller="InputCtrl"> <table> <tr> <td>This works. (input="text" + maxlength)</td> </tr> <tr> <td> <input type="text" ng-model="input1" maxlength="10"/> </td> </tr> <tr> <td>This doesn't. (input="number" + maxlength)</td> </tr> <tr> <td> <input type="number" ng-model="input2" maxlength="10"/> </td> </tr> <tr> <td>Therefore uses this. (input="number" + maxlength + directives)</td> </tr> <tr> <td><input type="number" ng-model="input3" maxlength="10" input-max-length-number/></td> </tr> </table> </div> </body>