1

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?

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

That's is that I wanted! Thank you so much!
1

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>

2 Comments

Only hide the div "A" but not hide the div "B" when "toggle".
I only showed one controller and div/button...the other would be same except for value in ng-show

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.