Ulises Vargas De Sousa Ulises Vargas De Sousa - 1 year ago 46
AngularJS Question

Real toggle button between different controllers in AngularJS

I want to create a simple button that toggle between two

s as follow:

<div ng-controller="A">

<div ng-controller="B">

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 Source

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