简体   繁体   中英

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.

It doesn't work because your controller isn't defined, thus throwing an error, breaking the angular directive too.

Just define the controller in your JS:

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

and it should work ( Updated JSFiddle )

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM