【问题标题】:Angular textarea directive: numbers allowed, no commas, dots allowed?角度文本区域指令:允许数字,不允许逗号,允许点?
【发布时间】:2015-05-22 08:06:22
【问题描述】:

我有一个 textarea,它将多个值作为数组保存在 ng-model 中。在按下回车键并插入新的有效字符(数字和点)时,会在数组中创建一个新值。

我正在尝试调整我在答案中找到的自定义指令。但是我还是有以下问题:

1- 您仍然可以输入连续的点为 (34...5),这是不允许的。
2-如果同一个键被按下两次,直到按下一个新键为止。因此,如果我按下字符“d”例如两次,它将在文本区域内呈现。
3-如果按下它们,我还希望将昏迷转换为点的指令。
4-新值必须以数字而不是点开头和结尾。
5- 每个数组值只有一个点。

这是我的代码:

视图/模板:

<script type="text/ng-template" id="form_field_float">
  <textarea only-digits class="form-control" rows="{{dbo.attributes[attobj.name].length + 2}}" ng-model="dbo.attributes[attobj.name]" ng-list="&#10;" ng-trim="false" ng-change="dbo._isDirty = true"></textarea>
</script>

指令:

 app.directive('onlyDigits', function () {

      return {
          restrict: 'A',
          require: '?ngModel',
          link: function (scope, element, attrs, ngModel) {
              if (!ngModel) return;
              ngModel.$parsers.unshift(function (inputValue) {

                  var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s != ' ' || s == "."); }).join('');
                  console.log(inputValue);
                  ngModel.$viewValue = digits;
                  ngModel.$render();
                  return digits;
              });
          }
      };
  });

【问题讨论】:

  • 我希望这里最简单的方法是定义一个正则表达式(是的,我知道,有两个问题等)并在文本更改时检查它 - 如果文本不再与正则表达式匹配,请将其恢复为旧值
  • 我尝试了正则表达式但没有成功,也许我应该更加努力...
  • 这是我的意思的 JSFiddle 示例jsfiddle.net/9mrLy4fL/1
  • 不错!那更好!谢谢

标签: javascript angularjs angular-directive


【解决方案1】:

replace()中的指令中的ok正则表达式是最后的解决方案:

模板:

<script type="text/ng-template" id="form_field_float">
  <textarea only-flo class="form-control" rows="{{dbo.attributes[attobj.name].length + 2}}" ng-model="dbo.attributes[attobj.name]" ng-list="&#10;" ng-trim="false" ng-change="dbo._isDirty = true"></textarea>
</script>

指令:

  app.directive('onlyFlo', function () {

      return {
          restrict: 'A',
          require: '?ngModel',
          link: function (scope, element, attrs, ngModel) {
              if (!ngModel) return;
              ngModel.$parsers.unshift(function (inputValue) {

                  //var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s != ' ' || s == '.'); }).join('');
                  var digits=  inputValue.replace(/\.{2,}/g, '.').replace(/e{2,}/gmi, 'e').replace(/[^0-9\.\n\r\-e]/gmi, '');
                  //var digits=  inputValue.split(/\s/).filter(function(s){return isNaN(s) ? false : s}).join('\r');
                  console.log('dig: ' +digits);
                  console.log(inputValue);

                  ngModel.$viewValue = digits;
                  ngModel.$render();
                  return digits;
              });
          }
      };
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多