Toggle between elements on button click AngularJS

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>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top