Change style in ng-click and after a while return to normal with Angularjs

Asked

Viewed 549 times

2

I have the following problem: I need a field to be shown in a solution with a "mask" as if it were hidden. When an event occurs or a click on a button (or itself) such field is filled with a value and after a while it is shown again with its "mask". Thus:

In HTML

<div ng-click="mudaCampo()">
    {{campo}}
</div>

In the JS

$scope.campo = '*****';

$scope.valorCampo = 'ola mundo';

$scope.mudaCampo = function(){

    //mostro o valor real do campo, existente em outra variável
    $scope.campo = $scope.valorCampo;

    //volta o valor mostrado no html para a "mascara" anterior
    setTimeout(function(){
        $scope.campo = '*****'; 
    },2000);

};

My problem is that $scope.campo even changes to the value of $scope.valorCampo but the function setTimeout does not return the value of the same for the previous mask... help?

Note I even tried to see how the $timeout but when I try to use the same one Angular accuses an error about the absence of the event...

  • 1

    Most likely and missing the $scope.$apply() so that the field value is changed. Try using [$timeout](https://docs.angularjs.org/api/ng/service/$timeout) instead of setTimeout since the first, by default calls the $scope.$apply (see the documentation)

1 answer

2

As reported by @Omni, I went after the $timeout and I realized that I was using it incorrectly. To be honest I also didn’t know the $scope.$apply that applies the existing changes in my controller... basically looked like this:

In the JS

$scope.campo = '*****';

$scope.valorCampo = 'ola mundo';

$scope.mudaCampo = function(){

    //mostro o valor real do campo, existente em outra variável
    $scope.campo = $scope.valorCampo;

    //volta o valor mostrado no html para a "mascara" anterior
    $timeout(function(){
        $scope.campo = '*****';
    },1000);

};

Recalling that, it is necessary to declare the $timeout as a dependency on my controller otherwise it does not work.

Browser other questions tagged

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