如何在ng-message中获取ng-maxlength的长度值

时间:2016-06-20 06:44:38

标签: angularjs ng-messages

在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>

2 个答案:

答案 0 :(得分: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来验证长度。

这是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);
      };
    }
  };
};

答案 1 :(得分: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>