angularjs – 显示自定义错误ngMessage

前端之家收集整理的这篇文章主要介绍了angularjs – 显示自定义错误ngMessage前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
In this plunk的目标是根据控制器中的验证显示错误消息(而不是所需的内置函数或最小长度).设置ng-message-exp时,不显示消息错误.任何想法如何使这项工作?

HTML

<body ng-app="ngMessagesExample" ng-controller="ctl">

  <form name="myForm" novalidate ng-submit="submitForm(myForm)">
    <label>
      This field is only valid when 'aaa' is entered  
      <input type="text"
             ng-model="data.field1"
             name="field1" />
    </label>
    <div ng-messages="myForm.field1.$error" style="color:red">
        <div ng-message-exp="validationError">this is the error</div>
    </div>

  <br/><br/>
  <button style="float:left" type="submit">Submit</button>
</form>

使用Javascript

var app = angular.module('ngMessagesExample',['ngMessages']);

app.controller('ctl',function ($scope) {

  $scope.submitForm = function(form) {

    if (form.field1.$modelValue != 'aaa') {
        $scope.validationError = true;
        console.log('show error');
    }
    else {
        $scope.validationError = false;
        console.log('don\'t show error');
    }
  };


});
您的主要ng-messages参数绑定到myForm.field1.$error,但您实际上从未向form.field1.$error添加错误.因此,在您的控制器中,只需通过$setValidity(field,isValid)手动向$error对象添加错误
if ($scope.data.field1 != 'aaa') {
    form.field1.$setValidity('validationError',false);
    // Angular will make form.field1.$error.validationError = true;
}
else {
    form.field1.$setValidity('validationError',true);
    // Angular will make form.field1.$error.validationError = false;
}

然后,您可以让ng-message指令执行其工作.提供ng-message的子元素已被评估为其父ng消息的属性(请注意额外的s).通常,这与父元素是表单元素的$error对象一起使用,内部子元素是$error.required或者你的情况$error.validationError.这里不需要ng-message-exp:

<div ng-messages="myForm.field1.$error" style="color:red">
    <div ng-message="validationError">this is the error</div>
</div>

Fixed plunker

原文链接:https://www.f2er.com/angularjs/143738.html

猜你在找的Angularjs相关文章