Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

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.

What I have tried:

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>

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:


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?
Updated 12-Sep-16 2:44am
Karthik_Mahalingam 12-Sep-16 9:27am    
does it works on normal javascript?

1 solution

As this is my first ever answer on here, excuse me for possible mistakes.

Data bindings in Angular work by a thing called digest cycle, which whenever called checks for differences between your view and your model. If you call a function from your view like you do with

it's automatically wrapped in an $apply() funtion, which starts an digest cycle and updates your view. When your timeout then completes the boolean changes to false, but Angular doesn't know, so you have to either call $apply() manually or use the $timeout service angular has build in.
Maybe try this link where this topic is explained further Understanding Angular&#039;s $apply() and $digest()[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900