简体   繁体   中英

ng-if/ng-hide doesn't get updated on real time on HTML page

I need some help in implementing a small change in angularJs with typescript. I basically need to change the text of a button for 3 seconds from the time it is being clicked, and revert the original text after 3 seconds are over. For this, I have created 2 html elements (buttons). I have applied ng-if directive for this purpose. Basically my aim is is as soon as the first button is clicked, it should get hidden and the other button should be displayed for just 3 seconds. After 3 seconds, the first button should come again.

Following are the 2 html buttons:

<div class="action">
                            <button class="configure-link" ng-if="!showPhoneNumber" ng-click="testAudio()">Listen</button>
                            <button class="configure-link" ng-if="showPhoneNumber"> Calling {{phonenumber}}</button>
</div>

As we can see, 'showPhoneNumber' is a boolean variable. When it is false, first button should be visible, and when it is true, second button should be visible. Following is the way I am changing the value of this boolean variable in typescript file:

Typescript:

scope.showPhoneNumber = false;
scope.testAudio = () =>{
scope.showPhoneNumber = true;
                setTimeout(function () { scope.showPhoneNumber = false }, 3000);
}

As soon as I click the first button, showPhoneNumber becomes true and first button gets hidden and I can see the second button. However the problem is, it is taking much more than 3 seconds (around 20 seconds) to get reverted and showing the first button again. Why ng-if is not getting binded from true to false after 3 seconds. I am not sure where I am going wrong. Can you please help?

Because you are using setTimeout function and not $timeout Angular service. Angular doesn't know that something has changed on scope until $apply is called. Possible fixes:

  • call scope.apply after setting scope.showPhoneNumber to false in your timeout callback
  • use $timeout Angular service

As already mentioned, setTimeout won't notify Angular and that's why is best practice to use $timeout instead. However, you can still keep your old code, just add $apply(); after scope.showPhoneNumber = false; like this:

setTimeout(function () { 
  scope.showPhoneNumber = false;
  $apply();
}, 3000);

If you want to know why and when to use $apply() , have a look at this post: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM