0

是否可以使用标准 Angular 机制存储一些额外的数据以及错误标志本身?即我手动设置ngModel.$setValidity,我想传递一些数据以及错误标志,以显示在ngMessages指令中。例如,假设字段的最小/最大长度取决于一些外部因素,因此是在服务器端计算和验证的。服务器响应customlength错误代码以及maxmin想向用户显示的属性。目前我只是设置ngModel.$setValidity("customlength", false);,但我想传递{max: response.max, min: response.min},在模板中插值<div ng-message="customlength">the length should be between {{ data.min }} and {{ data.max }}

4

1 回答 1

0

我想传递 {max: response.max, min: response.min} ,以便在模板中插值,就像长度应该在 {{ data.min }} 和 {{ data.max }} 之间

使用根范围存储要在消息字符串中输出的值:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.js"></script>
<script>
  angular.module('ngMessagesExample',['ngMessages']);
</script>
  
<body ng-app="ngMessagesExample">
  <form name="myForm" id="{{$root.$id}}">
  <label>
    <p>Enter Min:<input type="text" ng-model="form_min">
    <p>Enter Max:<input type="text" ng-model="form_max">
    <p>Enter your name:
    <input type="text"
           name="myName"
           ng-model="name"
           ng-minlength="form_min"
           ng-maxlength="form_max"
           required />
  </label>
   <p>
   <input type="radio" required name="foo" ng-model="foo" value="1">Yes
   <input type="radio" required name="foo" ng-model="foo" value="2">No
   </p>
   <p>
   Foo: <input type="text" ng-model="myForm.foo.$modelValue">
   </p>
   <p>
   <input type="submit" value="{{myForm.foo.$error.required ? 'No' : 'Yes'}}">
   </p>
  <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>

  <div ng-messages="myForm.foo.$error"   style="color:maroon" role="alert">
    <div ng-message="required">Pick one</div>
  </div>
  
  <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
    <div ng-message="required">Your value should be between {{form_min}} and {{form_max}} characters long</div>
    <div ng-message="minlength" id="{{$id}}">Your value is less than {{form_min}}</div>
    <div ng-message="maxlength" id="{{$id}}">Your value is greater than  {{form_max}}</div>
  </div>
</form>
</body>

参考

于 2016-02-12T16:36:58.523 回答