how can I select a tab from outside controller

2019-08-30 06:49发布

问题:

I'm using Tabs (ui.bootstrap.tabs) control\directive described here. The control creates it's own controller which sets active tab:

.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
  var ctrl = this,
      tabs = ctrl.tabs = $scope.tabs = [];

  ctrl.select = function(selectedTab) {
    angular.forEach(tabs, function(tab) {
      if (tab.active && tab !== selectedTab) {
        tab.active = false;
        tab.onDeselect();
      }
    });
    selectedTab.active = true;
    selectedTab.onSelect();
  };

Tabset child tab controls (child elements) can trigger parent's select function when clicked on them.

.directive('tab', ['$parse', function($parse) {
  return {
    require: '^tabset',
    scope: {
      onSelect: '&select',

I have my custom controller upwards the DOM which needs to trigger select function on TabsetController to set first tab active. I've read that I could use event broadcasting but I can't modify TabsetController to bind event listener so this doesn't seem to be a viable option. Any suggestions?

EDIT:

Please see Plunker for better understanding - here.

回答1:

You can declare a scope attribute within the "parent" controller and it will be accessible in the child controller. see: AngularJS - Access to child scope

Because TabsetController is set on a child DOM element while the MainController is set on a parent element, you can define and manipulate $scope.tabs in the MainController, and it will be seen and intepreted in TabsetController.