Vandervals Vandervals - 3 months ago 15
AngularJS Question

How to use multiple AngularJS nested / related controllers

I'm trying to generate an app that has 2 diferent tabs that are shown or hidden depending on 2 buttons that are controled by angular. At the same time inside those tabs there must be some independent forms.

I'm trying to add independent controllers for those tabs but as they are "inside" the mainController, I get an error. Maybe this is not the right approach but I'm trying to figer out what is the best solution for this.

This is the code I got previously to starting adding new controllers and getting those errors (obviously the content of the tabs is simplified):



var app = angular.module('myapp', [])
.controller('MainController', mainController);

function mainController() {
this.current_panel = "tab1";
this.change_panel = function(new_state){
this.current_panel = new_state;
}
}

<div class="wrapper" ng-app="myapp" ng-controller="MainController as ctrl">
<button ng-click="ctrl.change_panel('tab1')">Tab1</button>
<button ng-click="ctrl.change_panel('tab2')">Tab2</button>

<div class="tab1" ng-show="ctrl.current_panel == 'tab1'">
Tab1
<input type="text" ng-model="ctrl.txt"/>
{{ctrl.txt}}
</div>

<div class="tab2" ng-show="ctrl.current_panel == 'tab2'">
Tab2
<input type="text" ng-model="ctrl.txt"/>
{{ctrl.txt}}
</div>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>





Is there a way to have different controllers for those tabs? Should I discard the option of controlling the display of the tabs with angular and focus only using Angular for the tabs? Or should I have the methods for the both tabs inside the same controller?

Answer

You can declare 2 controllers outside your main and then in the html

  <div ng-controller="tab1ctrl as ctrl" class="tab1" ng-show="$parent.ctrl.current_panel == 'tab1'" >
  Tab1
    <input type="text" ng-model="ctrl.txt"/>
    {{ctrl.txt}}
  </div>

  <div ng-controller="tab2ctrl as ctrl" class="tab2" ng-show="$parent.ctrl.current_panel == 'tab2'">
  Tab2
    <input type="text" ng-model="ctrl.txt"/>
    {{ctrl.txt}}
  </div>