How ng-message is connected to model, and how can I show the message using ng-message?

前端 未结 3 1267
盖世英雄少女心
盖世英雄少女心 2021-01-01 19:13

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). Th

3条回答
  •  余生分开走
    2021-01-01 19:48

    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;
    }
    

    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:

    this is the error

    Fixed plunker

提交回复
热议问题