Ulises Vargas De Sousa
Ulises Vargas De Sousa

Reputation: 847

Real toggle button between different controllers in AngularJS

I want to create a simple button that toggle between two divs as follow:

<div ng-controller="A">
</div>

<div ng-controller="B">
</div>

Being "A" my main controller, the one that I want to display first.

If I suppose that my button is in "A", I could hide my "A" div and show my "B" div, when I clicked, and when I clicked again hide my "B" div and show my "A" div?

It is possible?

Upvotes: 1

Views: 304

Answers (2)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

What charlietfl mentioned is perfectly correct. But you can also use $rootScope to achieve the same but generally, it is not recommended to use $rootScope. So you can use the following approach.

Create a global controller like GlobalController and add it to the body or the html tag so that it's scope is available throughout your app. There you can add a method to toggle between different controllers:

var app = angular.module("sa", []);

app.controller("GlobalController", function($scope) {
  $scope.globalData = {
    current: "A"
  };

  $scope.toggleSection = function() {
    $scope.globalData.current = $scope.globalData.current == "A" ? "B" : "A";
  };
});

app.controller("A", function($scope) {});
app.controller("B", function($scope) {});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="sa" ng-controller="GlobalController">

  <div ng-controller="A" ng-show="globalData.current == 'A'">
    I'm A. <a href="" ng-click="toggleSection()">Display B</a>
  </div>

  <div ng-controller="B" ng-show="globalData.current == 'B'">
    I'm B. <a href="" ng-click="toggleSection()">Display A</a>
  </div>

</body>

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

It is possible?

Sure...multiple ways to do it. The first way you usually want to look at is using a service to share data across various components of the app.

angular.module('myapp').service('ButtonService', function(){
     this.active = 'A';
     this.toggleActive = function(){
       this.active =   this.active === 'A' ? 'B' :'A';
     }    
});

angular.module('myapp').controller('A', function($scope, ButtonService){
   $scope.state = ButtonService;    
});
// repeat in B controller

Then in the view do something like:

<div ng-show="state.active == 'A'">
   <button ng-click="state.toggleActive()">Toggle Div's</button>

Upvotes: 1

Related Questions