Search code examples
javascriptangularjsangularjs-ng-include

Having multiple controllers for very same html file


hope you can help me with this one:

HTML:

    <div role="tabpanel" ng-controller="tabController">
        <ul class="nav nav-pills nav-tabs" role="tablist">
            <li role="presentation" ng-repeat="tab in tabs" ng-click="selectTab($index)" ng-class="{'active':selectedTab == $index}">
                <a data-target="#tab" aria-controls="home" role="tab" data-toggle="tab">Tab {{tab.id}} <span ng-click="deleteTab($index)" class="glyphicon glyphicon-remove"></span></a>
            </li>
            <li role="presentation" class="nav-pills" ng-click="addTab()">
                <a aria-controls="home" role="tab" data-toggle="tab">( + )</a>
            </li>
        </ul>
        <content ng-hide="counter === 0" ng-include="tabs[selectedTab].content">
        </content>
    </div>

JS:

angular.module('App')
.controller('tabController', function ($scope) {
    /** holds tabs, we will perform repeat on this **/
    $scope.tabs = [];

    // ContollerS for this => <content ng-hide="counter === 0" ng-include="tabs[selectedTab].content">
    $scope.currentTabController = null;

    // Hold controllers here;
    $scope.tabControllersList = [];

    $scope.counter = 0;
    /** Function to add a new tab **/
    $scope.addTab = function () {
        $scope.counter++;
    var tabController = new TabController();
    $scope.tabControllersList.push(tabController);
        $scope.tabs.push({ id: $scope.counter, content: tabController });
        $scope.selectedTab = $scope.tabs.length - 1; //set the newly added tab active. 
    }

    /** Function to delete a tab **/
    $scope.deleteTab = function (index) {
        $scope.tabs.splice(index, 1); //remove the object from the array based on index
    }

    $scope.selectedTab = 0; //set selected tab to the 1st by default.

    /** Function to set selectedTab **/
    $scope.selectTab = function (index) {
    // Add controller with all data and state.
    $scope.currentTabController = $scope.tabControllersList[index];
        $scope.selectedTab = index;
    }
});

So I want to have a separate controller for each tab (template for tabs the same - test.html), so when I switch tabs it would preserve data and chages in each of them. Is it possible?

Thank you in advance!


Solution

  • Actually I realized that in this case I need multiple models, not controllers. So view is the same, controller is the same, but I've added service to store and restore my models and on tab switch $rootScope.$broadcast('onTabChanged', index); I just swap to corresponding model.