Ulises Vargas De Sousa Ulises Vargas De Sousa - 5 months ago 8
AngularJS Question

Real toggle button between different controllers in AngularJS

I want to create a simple button that toggle between two

div
s 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?

Answer

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>