本文介绍了ng-message如何与模型连接,如何使用ng-message显示消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此插件中的目的是显示基于验证的错误消息控制器(而不是内置的requiredmin-length).设置ng-message-exp时,不显示消息错误.关于错误或模型的任何想法,或者如何更好地实现ng-message实际工作的方式,这些想法都与错误或模型有关?

In this plunk the objective is to show an error message based on validation in the controller (instead of the built-ins required or min-length). The message error does not display when the ng-message-exp is set.Any idea on how to make this work or better how ng-message actually works which is tied to the error or model?

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

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对象:

Your main ng-messages argument is tied to myForm.field1.$error, but you never actually add an error to the form.field1.$error. So in your controller, just manually add an error to the $error object via $setValidity(field, isValid):

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-messages的属性(请注意额外的s).因此,通常将其与父元素一起用作表单元素的$error对象,而内部子元素则与$error.required或您的情况下$error.validationError等属性一起使用.无需ng-message-exp此处:

Then, you can just have the ng-message directive do its work. The child elements that provide ng-message are evaluated as properties of their parent ng-messages already (note the extra s). So typically, this is used with the parent being the form element's $error object and the inner children are the properties like $error.required or in your case $error.validationError. No need for ng-message-exp here:

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

固定的塞子

这篇关于ng-message如何与模型连接,如何使用ng-message显示消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 01:43