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

1

I am able to use to perform invalid input validations, min characters and max characters, eg:

<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 show a message if 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.");
        });
    };
});

In http error, I need to send an action to show console.log () message

Example working on plunker

    
asked by anonymous 15.04.2016 / 18:24

2 answers

0

I was able to solve, 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 like this:

<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 $scope I changed it 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 at plunker

    
15.04.2016 / 19:55
1

As far as I know from ngMessage , to create a non-default validation, you would need to bind this to a custom directive where it would do this validation and consequently you can display the error. I at least am not aware of a method of using 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 form integrated validation, 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
            }
        }
    };
});

Comments:

- I did not get to test this application template with $http service, I just used it for basic comparisons, like checking if the password in two fields is the same, but the idea is this.

- An improvement, let's say, for your messages would be to use $dirty in conjunction with $error , so the message only appears after interaction with the form and not just at the beginning, before the user interacts. See:

<div ng-messages="myForm.cep.$dirty && myForm.cep.$error">
    
15.04.2016 / 19:11