126

我有一个文本输入,我不想让用户使用空格,输入的所有内容都会变成小写。

我知道我不允许在 ng-model 上使用过滤器,例如。

ng-model='tags | lowercase | no_spaces'

我看着创建自己的指令,但添加函数$parsers并且$formatters没有更新输入,只有其他元素ng-model

如何更改我当前正在输入的输入?

我本质上是在尝试创建类似于 StackOverflow 上的“标签”功能。

4

9 回答 9

207

我相信 AngularJS 输入和指令的意图ngModel无效输入永远不应该出现在模型中。该模型应始终有效。拥有无效模型的问题是我们可能有观察者基于无效模型触发并采取(不适当的)动作。

正如我所看到的,这里正确的解决方案是插入$parsers管道并确保无效输入不会进入模型。我不确定你是如何尝试处理事情的,或者什么对你不起作用,$parsers但这里有一个简单的指令可以解决你的问题(或者至少是我对问题的理解):

app.directive('customValidation', function(){
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {

       modelCtrl.$parsers.push(function (inputValue) {

         var transformedInput = inputValue.toLowerCase().replace(/ /g, ''); 

         if (transformedInput!=inputValue) {
           modelCtrl.$setViewValue(transformedInput);
           modelCtrl.$render();
         }         

         return transformedInput;         
       });
     }
   };
});

一旦声明了上述指令,就可以像这样使用它:

<input ng-model="sth" ng-trim="false" custom-validation>

正如@Valentyn Shybanov 提出的解决方案一样,ng-trim如果我们想在输入的开头/结尾禁止空格,我们需要使用该指令。

这种方法的优点是 2 倍:

  • 无效值不会传播到模型
  • 使用指令很容易将此自定义验证添加到任何输入,而无需一遍又一遍地复制观察者
于 2013-01-20T13:31:48.080 回答
29

我建议观看模型值并在更改时对其进行更新:http://plnkr.co/edit/Mb0uRyIIv1eK8nTg3Qng? p =preview

唯一有趣的问题是空格:在 AngularJS 1.0.3 中,输入时 ng-model 会自动修剪字符串,因此如果您在末尾或开头添加空格,它不会检测到模型已更改(因此我的空格不会自动删除代码)。但是在 1.1.1 中有一个 'ng-trim' 指令允许禁用这个功能(commit)。因此,我决定使用 1.1.1 来实现您在问题中描述的确切功能。

于 2013-01-19T23:31:16.757 回答
23

解决此问题的方法可能是在控制器端应用过滤器:

$scope.tags = $filter('lowercase')($scope.tags);

不要忘记声明$filter为依赖项。

于 2014-01-14T11:16:05.413 回答
10

如果您使用的是只读输入字段,则可以将 ng-value 与过滤器一起使用。

例如:

ng-value="price | number:8"
于 2017-12-10T22:36:55.860 回答
5

使用添加到 $formatters 和 $parsers 集合的指令来确保在两个方向上执行转换。

有关更多详细信息,请参见其他答案,包括指向 jsfiddle 的链接。

于 2015-10-20T12:34:49.853 回答
3

我有类似的问题并使用

ng-change="handler(objectInScope)" 

在我的处理程序中,我调用 objectInScope 的一个方法来正确修改自身(粗略输入)。在控制器中,我在某个地方启动了

$scope.objectInScope = myObject; 

我知道这不使用任何花哨的过滤器或观察者......但它很简单而且效果很好。唯一的缺点是 objectInScope 在对处理程序的调用中发送......

于 2014-10-07T17:25:12.387 回答
1

ng-model如果您正在执行复杂的异步输入验证,那么将一个级别抽象为具有自己验证方法的自定义类的一部分可能是值得的。

https://plnkr.co/edit/gUnUjs0qHQwkq2vPZlpO?p=preview

html

<div>

  <label for="a">input a</label>
  <input 
    ng-class="{'is-valid': vm.store.a.isValid == true, 'is-invalid': vm.store.a.isValid == false}"
    ng-keyup="vm.store.a.validate(['isEmpty'])"
    ng-model="vm.store.a.model"
    placeholder="{{vm.store.a.isValid === false ? vm.store.a.warning : ''}}"
    id="a" />

  <label for="b">input b</label>
  <input 
    ng-class="{'is-valid': vm.store.b.isValid == true, 'is-invalid': vm.store.b.isValid == false}"
    ng-keyup="vm.store.b.validate(['isEmpty'])"
    ng-model="vm.store.b.model"
    placeholder="{{vm.store.b.isValid === false ? vm.store.b.warning : ''}}"
    id="b" />

</div>

代码

(function() {

  const _ = window._;

  angular
    .module('app', [])
    .directive('componentLayout', layout)
    .controller('Layout', ['Validator', Layout])
    .factory('Validator', function() { return Validator; });

  /** Layout controller */

  function Layout(Validator) {
    this.store = {
      a: new Validator({title: 'input a'}),
      b: new Validator({title: 'input b'})
    };
  }

  /** layout directive */

  function layout() {
    return {
      restrict: 'EA',
      templateUrl: 'layout.html',
      controller: 'Layout',
      controllerAs: 'vm',
      bindToController: true
    };
  }

  /** Validator factory */  

  function Validator(config) {
    this.model = null;
    this.isValid = null;
    this.title = config.title;
  }

  Validator.prototype.isEmpty = function(checkName) {
    return new Promise((resolve, reject) => {
      if (/^\s+$/.test(this.model) || this.model.length === 0) {
        this.isValid = false;
        this.warning = `${this.title} cannot be empty`;
        reject(_.merge(this, {test: checkName}));
      }
      else {
        this.isValid = true;
        resolve(_.merge(this, {test: checkName}));
      }
    });
  };

  /**
   * @memberof Validator
   * @param {array} checks - array of strings, must match defined Validator class methods
   */

  Validator.prototype.validate = function(checks) {
    Promise
      .all(checks.map(check => this[check](check)))
      .then(res => { console.log('pass', res)  })
      .catch(e => { console.log('fail', e) })
  };

})();
于 2016-05-02T17:24:13.020 回答
0

我来这里是为了寻找一种解决方案,该解决方案可以主动更改输入文本,并在我们键入时用 * 屏蔽除最后 4 位以外的所有数字。这是通过 $formatters 实现的

eg: Account Num 输入框:1234567890AHSB1应该在输入框中显示为**********AHSB

答案只是上面@pkozlowski.opensource给出的答案的轻微变化。

angular.module('myApp').directive('npiMask', function() {
  return {
    require: 'ngModel',
    link: function($scope, element, attrs, modelCtrl) {
      modelCtrl.$formatters.push(function(inputValue) {
        var transformedInput = inputValue.toString().replace(/.(?=.{4,}$)/g, '*');
        if (transformedInput !== inputValue) {
          modelCtrl.$setViewValue(transformedInput);
          modelCtrl.$render();
        }
        return transformedInput;
      });
    }
  };
});
<input-text 
 name="accountNum" 
 label="{{'LOAN_REPAY.ADD_LOAN.ACCOUNT_NUM_LABEL' | translate}}" 
 ng-model="vm.model.formData.loanDetails.accountNum" 
 is-required="true" 
 maxlength="35" 
 size="4" 
 npi-mask>
</input-text>

于 2022-02-16T23:39:34.077 回答
0

你可以试试这个

$scope.$watch('tags ',function(){

    $scope.tags = $filter('lowercase')($scope.tags);

});
于 2016-01-19T06:50:12.847 回答