【问题标题】:Custom character separator with ngModel is not working properlyngModel 的自定义字符分隔符无法正常工作
【发布时间】:2017-01-18 06:56:29
【问题描述】:

我想在 AngularJs 中用字符分隔符格式化文本框中输入的数字。

我创建了一个指令来进行格式化。该指令正在生成正确的输出,但无法正确更新 ngModel

<input type="text" data-ng-model="aadhaar" dashsep="'-'">

.directive('dashsep', function($timeout) {
  'use strict';
  return {
    restrict: 'A',
    scope: {
        dashsep: '=',
        ngModel: '=ngModel'
    },
    require: '?ngModel',
    link: function(scope, element, attr) {
        element.bind("keyup", function (event) {
            var formattedAdh = "";
            //console.log(element.val());

            var test = element.val().toString();

            for(var i=0;i<=test.length-1;i++){
                //console.log(test[i]);
                if(i%4 === 0 && i>0){
                    formattedAdh+= scope.dashsep;
                }
                formattedAdh += test[i];
            }

            // Following script is not updateing the ngModel/textbox with the formatted value properly //
            /*
                //element.val(scope.$eval(formattedAdh));
                // OR
                //scope.ngModel = formattedAdh;
            */

            // Following output is showing proper value IF ABOVE SCRIPT IS COMMENTED //
            console.clear();
            console.log(formattedAdh);
        });
     }
   };
 });

Plunker 中提供了完整的脚本。

【问题讨论】:

    标签: angularjs-directive angular-ngmodel


    【解决方案1】:

    根据我对示例代码的理解,我认为您正试图在每 4 个字符后添加一个破折号。也就是说,当用户键入“aaaabbbbcccc”时,您希望“aaaa-bbbb-cccc”会显示在input[text] 中,并且范围模型会相应地更新。

    鉴于此假设,您需要使用格式化的视图值调用$setViewValue,而不是直接更新范围模型表达式。这很重要,因为$setViewValue 在更新范围模型表达式之前会将您的新视图值与ngModelController 的内部视图值和内部模型值同步。

    假设新的作用域模型已经成功改变——也就是说,它通过了解析器和验证器,那么$viewChangeListeners 将运行。从那里,您可以调用 $render 以使用新的视图值更新 DOM。

    这是 plunker 的更改。

    link: function(scope, element, attr, ngModelController) {
        element.on('keyup', function (event) {
          var viewValue = element.val().toString();
    
          // add a dash every 4 characters
          if ((viewValue.length + 1) % 5 === 0) {
            viewValue += scope.dashsep;
          }
    
          // angular updates the internal view value, internal model, then scope model based on DOM
          ngModelController.$setViewValue(viewValue, event);
        });
    
    
        ngModelController.$viewChangeListeners.push(function(){
          console.log(ngModelController.$modelValue);
          // when model changes, call $render to display the latest view value
          ngModelController.$render();
        });
    })
    

    如果您想更深入地了解 ngModelController,这篇文章可能会有所帮助:https://medium.com/product-at-catalant-technologies/i-have-to-relearn-angulars-form-api-every-time-i-use-it-83287c521968#.f5hle083e

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      相关资源
      最近更新 更多