0

在 ng-message 的消息中,如何获取在 ng-maxlength 中输入的值?
例如:

<form name="myForm">
    <input type="text"
           name="myName"
           ng-model="name"
           ng-maxlength="5"/>

  <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
    <div ng-message="maxlength">Please enter up to {{??}} characters</div>
  </div>
</form>
4

2 回答 2

0

把它放在一个变量中,这样你就可以重用它

<form name="myForm">
    <input type="text"
           name="myName"
           ng-model="name"
           ng-minlength="nameConstraint.maxlength"/>

  <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
    <div ng-message="maxlength">Please enter up to {{nameConstraint.maxlength}} characters</div>
  </div>
</form>

没有其他办法,maxLength 指令监视属性 maxlength 并使用 $validators 来验证长度。

这是 angular 中 maxlength 的代码指令:

var maxlengthDirective = function() {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope, elm, attr, ctrl) {
      if (!ctrl) return;
      var maxlength = -1;
      attr.$observe('maxlength', function(value) {
        var intVal = toInt(value);
        maxlength = isNaN(intVal) ? -1 : intVal;
        ctrl.$validate();
      });
      ctrl.$validators.maxlength = function(modelValue, viewValue) {
        return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
      };
    }
  };
};
于 2016-06-20T06:53:35.143 回答
0

试试用这个

<div  ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
  <div ng-if="name.length <= 5" >
     Please enter up to {{name.length}} characters 
  </div>
 </div>
于 2016-06-20T07:11:01.023 回答