简体   繁体   English

仅数字输入的自定义指令不适用于控制器绑定的div内的HTML

[英]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. 我正在为AngularJS JavaScript的仅数字输入搜索自定义指令,并获得了一个有效的指令,但是当我将其用于绑定到控制器的body或div中的输入框时,该指令不起作用。

HTML: 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 JSFiddle: 单击此处

It Works properly if I delete the controller part from the div. 如果我从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: 只需在JS中定义控制器:

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

and it should work ( Updated JSFiddle ) 它应该可以工作( 更新了JSFiddle

You have an undefined controller, removing it will fix it: 您有一个未定义的控制器,将其删除将对其进行修复:

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

Or create it 或创建它

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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