AngularJS 指令数字格式屏蔽 [英] AngularJS Directive Numeric Format Masking

查看:21
本文介绍了AngularJS 指令数字格式屏蔽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建的指令使用函数 setFormatting 来屏蔽输入字段中的文本值.

The directive I have created uses the function setFormatting to mask the text value in an input field.

scope.$watch(element, function() {
    modelCtrl.$setViewValue(setFormatting(element.val(), attrs.symbol));
    modelCtrl.$render();
});

element.bind('blur', function() {
    modelCtrl.$setViewValue(setFormatting(element.val(), attrs.symbol));
    modelCtrl.$render();
});

scope.$watch 在第一次加载/应用内容时应用掩码, element.bind 在其他时间应用掩码.scope.$watch 将符号(如果有)存储为 ng-model 变量的一部分.element.bind 不是.我认为 $setViewValue() 和 $render() 没有更新 ng-model 变量.在哪里更新变量?

The scope.$watch applies the mask when the content is loaded/applied the first time, the element.bind applies the mask for the other times. The scope.$watch is storing the symbol (if there is one) as part of the ng-model variable. The element.bind is not. I thought $setViewValue() and $render() did not update the ng-model variable. Where is the variable being updated?

见附件小提琴:http://jsfiddle.net/PJ3M4/
谢谢.

See attached fiddle: http://jsfiddle.net/PJ3M4/
Thanks.

推荐答案

通过添加 modelCtrl.$parsers.push() { ... },我能够让 ng-model 以我想要的方式存储值到我的范围.$watch() { ... }.

I was able to get the ng-model to store values the way I wanted to by adding a modelCtrl.$parsers.push() { ... } to my scope.$watch() { ... }.

scope.$watch(element, function() {
    modelCtrl.$parsers.push(function(inputValue) {
        showAlert("Watch", 1);

        if (!prev) {
            prev = false;
            var returnVal = checkVal(inputValue, modelCtrl, decimals, true, minVal, maxVal);

            if (String(returnVal) === ".") {
                setAndRender(modelCtrl, "");
                return "";
            }
            else {
                return returnVal;
            }
        }
        return String(inputValue).replace(/[^0-9 . -]/g, '');
    });

    prev = true;
    setAndRender(modelCtrl, setFormatting(element.val(), decimals, attrs.prefix, attrs.symbol));
});

这篇关于AngularJS 指令数字格式屏蔽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆