Search code examples
javascriptangularjs

Toggle between elements on button click AngularJS


I have two divs and want to toggle between them by clicking on button. The following is the code I have tried:

<div id="one" *ngIf="show == true">
     Hello One
</div>
<div id="two" *ngIf="show == false">
     Hello Two
</div>
<button ng-init="show=true">Click to toggle</button>

I want to toggle between two divs on button click, somehow it is not happening in this case. I am suspecting that show is never set to false. What could be my mistake. I am a rookie in AngularJS. How can I achieve toggle btween two elements on button click? Thanks in advance.


Solution

  • First of all, instead of *ngIf, you have to write ng-if. The former notation is for Angular and the latter is for AngularJS (the predecessor of Angular, which you are using).

    Secondly, you are right that show is never set to false in your code. You need to write a function in the controller that can toggle the value of show, as follows:

    constructor($scope) {
    
        $scope.show = true;
        $scope.toggle = function(){
            $scope.show =!$scope.show;
        }
    }
    

    Then, the html can be as follows:

    <div id="one" ng-if="show">
         Hello One
    </div>
    <div id="two" ng-if="!show">
         Hello Two
    </div>
    <button ng-click="toggle()">Click to toggle</button>