Thursday, February 6, 2014

Angularjs - number only input directives

app.js:
app.directive('numberOnly', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            ngModel: '='
        },
        link: function (scope) {          
            scope.$watch('ngModel', function(newValue,oldValue) {        
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.ngModel = oldValue;
                }
            });
        }
    };
});

app.controller('MainCtrl', function($scope) {
  $scope.name = 0;
});

html:
<body ng-controller="MainCtrl">
    <input type="text" ng-model="name" number-only/>
</body>


That's it and simple.
demo here

No comments: