DeathNote DeathNote - 2 months ago 4
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.


<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>


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) {
return transformedInput;
return undefined;

JSFiddle: Click Here

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


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

Or create it

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