How to disable field and button in angularJS?

3

I have a text field and button to send that text. You are having a small delay , after I click the send button until the message is sent. Then I need to disable the text field and the button until the message is sent and appears on the screen, then enable them again. How can I do this using Angular?

HTML:

<label class="item-input-wrapper">
    <input type="text" ng-focus="inputUp()" ng-blur="inputDown()" ng-disabled="!mensagem" ng-model="mensagem.msg" placeholder="Texto" />
</label>
<button class="button button-small" ng-click="enviarMsg(mensagem)">Enviar</button>

controller:

$scope.enviarMsg = function (mensagem) {
    //console.log(mensagem);
    var dia = moment().format(); //2016-02-16 T 16:05:52-02:00
    var diaP = dia.split('T');
    var dia = diaP[0];

    var horaP = diaP[1];
    var horaP2 = horaP.split(':');
    var hora = horaP2[0]+':'+horaP2[1];

    var enviaMsg = {
        mensagem: mensagem,
        idUsuario: $window.localStorage.getItem('idUsuario'),
        idCep: $window.localStorage.getItem('idCep'),
        nome: $window.localStorage.getItem('nome'),
        dia: dia,
        hora: hora
    }

    $http.post("http://www.vigilantescomunitarios.com/www/php/enviaMsgLogra.php", enviaMsg).success(function (data){
        //console.log(data);
        pegaMsgsLogra();
        $scope.mensagem = {
          msg: ""
        }

    });
}
    
asked by anonymous 25.02.2016 / 20:33

1 answer

2

You can create a Boolean variable to handle this problem. Ex:

$scope.disableButton = false;

At the beginning of the function enviarMsg you set the variable to true : $scope.disableButton = true; .

At the end, after sending the message, you just assign the variable as false again

Then just put the ng-disabled directive in the button code:

 <button class="button button-small" ng-click="onTimeout()" ng-disabled="disableButton">Enviar</button>

Example (I made a 5 second timer to simulate a request):

var myApp = angular.module('myApp', []);


myApp.controller('MyCtrl', function($scope, $timeout) {
    $scope.disableButton = false;

    $scope.counter = 0;
    $scope.onTimeout = function() {
        //Assim que entrar na função seta como true
        $scope.disableButton = true;
        $scope.counter++;
        mytimeout = $timeout($scope.onTimeout, 1000);
        if ($scope.counter >= 5) {
            $timeout.cancel(mytimeout);
            //Depois de terminar a requisição seta como false
            $scope.disableButton = false;
            $scope.counter = 0;

        }
    }


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp" ng-controller="MyCtrl">
   {{counter}}
   <button class="button button-small" ng-click="onTimeout()" ng-disabled="disableButton">Enviar</button>
</div>
    
25.02.2016 / 20:56