DeathNote DeathNote - 3 months ago 7
HTML Question

Custom Directive for number only input not working for HTML inside controller bound div

I was searching for custom directive for number only input for AngularJS JavaScript and I got hands on a working directive but it isn't working when I am using it for input box which is inside body or div bound to a controller.

HTML:

<div ng-app="app" ng-controller="xyz">
<p>Demo of AngularJS Numbers Only Directive</p>
<p>Input below will accept only numbers.</p>
<p><input type="text" ng-model="val" numbers-only /></p>
</div>


Script:

var app = angular.module('app', []);
app.directive('numbersOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9]/g, '');

if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return undefined;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});


JSFiddle: Click Here

It Works properly if I delete the controller part from the div.

Answer

You have an undefined controller, removing it will fix it:

http://jsfiddle.net/kgp0z2y9/3/

Or create it

app.controller('xyz', function(){});

http://jsfiddle.net/kgp0z2y9/5/