How do I use ng-messages to show $http errors?

Asked

Viewed 783 times

1

I am able to use to perform validations of empty input, min of characters and max of characters,example:

<form name="myForm">
  <div class="input-group">

    <input type="text" class="form-control" name="cep" ng-model="cep" ng-minlength="5" ng-maxlength="20" placeholder="Digite o CEP" autofocus required>

    <span class="input-group-btn">
     <button class="btn btn-success" type="submit" ng-click="buscar(cep)">
     <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
    </button>
    </span>
  </div>
</form>


<div ng-messages="myForm.cep.$error">
  <div ng-message="required" class="alert alert-danger" role="alert">Campo não pode ser vazio.</div>
  <div ng-message="minlength" class="alert alert-danger" role="alert">Deve ser acima de 5 caracteres</div>
  <div ng-message="maxlength" class="alert alert-danger" role="alert">Deve possuir menos que 20 caracteres</div>
</div>

Now I need to understand, how to use the same ng-message service to display a message in case my request fails example:

var app = angular.module("buscaCEP",['ngMessages']);
app.controller("buscaCEPCtrl",function($scope,$http){
    $scope.buscar = function(cep){
        $http.get('https://viacep.com.br/ws/'+cep+'/json/').success(function(data){
            $scope.form = data;
        }).error(function(){
            console.log("Ocorreu um erro inesperado, verifique se os dados digitados estão corretos.");
        });
    };
});

No. http error need to send an action to display the console message.log();

Example working on plunker

2 answers

1

From what I understand of ngMessage, to create a validation that is not standard, you would need to link this to a custom directive where it would do this validation and consequently you can display the error. I, at least, do not know a method of using the ng-messages from a $scope, for example.

Example:

<div ng-messages="myForm.cep.$error">
    <div ng-message="cepinvalido" class="alert alert-danger" role="alert">Cep inválido</div>
</div>

And a Directive that makes this validation integrated into the form, for example:

<input type="text" class="form-control" name="cep" ng-model="cep"  ng-minlength="5" ng-maxlength="20" placeholder="Digite o CEP" autofocus required cepinvalido>

app.directive("cepinvalido", function() {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attributes, ngModel) {
            ngModel.$validators.cepinvalido = function(modelValue) {
                //obter os dados e fazer o return caso não haja resposta do CEP
                    return false;

                //ou retornar os dados caso haja
                //Para isso precisaria expandir a lógica do form ou do directive
            }
        }
    };
});

Remarks:

-I didn’t get to test this application model with service $http, I just used it for basic comparisons, like checking if the password in two fields is the same, but that’s the idea.

-An improvement, shall we say, to your messages would be to use $dirty together with $error, so the message only appears after interaction with the form and not right at the beginning, before the user interacts. See:

<div ng-messages="myForm.cep.$dirty && myForm.cep.$error">
  • That one $dirty I was trying to do it and I didn’t know how...

1


I managed to resolve, as I am still a young padawan in angular do not know if it is the correct form or an Advanced RTA :)

I used ng-class thus:

<div class="alert alert-danger" ng-class='{"invisible": !resCep}' role="alert">
    Ocorreu um erro inesperado, verifique se os dados digitados estão corretos.
</div>

And in the $scope changed like this:

$http.get('https://viacep.com.br/ws/' + cep + '/json/').success(function(data) {
  $scope.form = data;
  $scope.resCep = false;
}).error(function() {
  $scope.resCep = true; // mostre o alert
});

See working on plunker

Browser other questions tagged

You are not signed in. Login or sign up in order to post.