javascript - AngularJS 输入类型 = 监视变化的数字的指令

标签 javascript angularjs input angularjs-directive

上下文:我正在开发我的应用程序的移动版本。我希望用户能够使用 numeric keybord 输入数字字段他们的手机/平板电脑。 AngularJS 使任何非整数数据(因为输入是字符串)都无法访问 type = "number" 的输入字段。

想法:我想制定一个指令,以某种方式(使用 $watch$parsers 或任何其他古老的巫术)将输入字符串转换为数字。

问题:当我在输入字段中键入任何内容时,我的指令不会触发 $watch 的更改。 但是当我从 Controller 更改作用域字段时,$watch 会按计划触发。

Controller :

        // code minimized and omitted for clarity
        .controller('carController', ['$scope', function ($scope) {
            $scope.car = {
                power : null,
                // other fields
            }
        }]);

指令

angular.module('numeric', []).directive('numeric', function () {
    return {
        restrict: 'A',
        require: 'ngModel',

        scope: {
            model: '=ngModel'
        },
        link: function (scope, element, attrs, ngModelCtrl) {
            // parsers does not affect anything
            ngModelCtrl.$parsers.push(function(value) {
                return parseInt(value);
            });

            // watcher does not watch
            scope.$watch('model', function(newVal, old) {
                if (typeof newVal == 'string') {
                    scope.car.power = parseInt(newVal);
                }
            }, true);

        }
    };
});

html

    <div ng-controller="carController">
     <input   
            ng-model="car.power"                      
            numeric
            name="power"
            type="number"
            pattern="[0-9]">
       </div>

这是一个演示这种行为的 fiddle http://jsfiddle.net/xo94sw7m/1/

问题:我缺少什么以及如何使指令按计划工作?


我尝试过的:使用$formatters-$parsers,使用不同的方法来$watch(使用scope:false,隔离范围,尝试使用attrs等来观察范围变化),到目前为止似乎没有任何效果

最佳答案

myApp.directive('number', ['$parse', function($parse) {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController) {

            ngModelController.$parsers.push(function(data) {
                return parseInt(data);
            });
            ngModelController.$formatters.push(function(data) {
                if (data) {
                    var model = $parse(attrs['ngModel']);
                    model.assign(scope, parseInt(data));
                }
                return parseInt(data);

            });
        }
    }
}]);

Here is working fiddle

关于javascript - AngularJS 输入类型 = 监视变化的数字的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42903820/

相关文章:

javascript - 将 sweetalert2 与 node.js 和express.js 一起使用

javascript - 对象中的鼠标事件处理

javascript - 使 UI Grid 的 ColumnsDef 动态化

javascript - 将多个输入值传递给函数以更新图像

Javascript:如何返回具有多组输入的函数总和

html - 如何将文本放在输入表单的前面?

javascript - 表单内提交函数

javascript - 提取 URL 的一部分

php - Angular - ng-flow如何将字符串与文件一起发送

angularjs - Firebase 与 AngularFire