linyuanxie
linyuanxie

Reputation: 787

How to access angular bootstrap UI from controller

I am trying to use angularJS bootstrap tabset, in my requirement, I need to add a next button to let customer to switch tabs. Here is my code:

<div ng-controller='ctr'>
  <tabset>
  <tab  active='sqTab' heading="tab1">
       tabt 1     
  </tab>
  <tab  active='psTab' heading="tab2">
       tabt 2    
  </tab>
  </tabset>
  <button click='next()')>next</button>
</div>

In the controller "ctr":

$scope.sqTab = true;
$scope.psTab = false;
$scope.next = function(){
 $scope.sqTab = false;
 $scope.psTab = true;
}

As you can see, I set active for each tab, it works fine when the page load,I can switch to tab2 after I hit next, but if I click tab head to switch back, and try to hit next button again, it didn't work,it may be the reason the directive is isolated scope, I can't access it's active, but if so why I can switch first time? Is there any way I can do it?

Upvotes: 0

Views: 486

Answers (2)

jbrown
jbrown

Reputation: 3025

Use a scope variable to enumerate through the tab indexes with a next and perhaps previous button.

HTML

  <button ng-click="previous()" ng-disabled="activeTab===0">Previous</button>
  <button ng-click="next()" ng-disabled="activeTab===1">Next</button>
  <div>
    <uib-tabset active="activeTab">
      <uib-tab index="0" heading="Tab 0">
        <div>This is tab 0</div>
      </uib-tab>
      <uib-tab index="1" heading="Tab 1">
        <div>This is tab 1</div>
      </uib-tab>
    </uib-tabset>
  </div>

Controller

  $scope.activeTab = 0;

  $scope.next = function() {
    $scope.activeTab += 1;
  };
  $scope.previous = function() {
    $scope.activeTab -= 1;
  };

Here's a working plunk.

Upvotes: 0

Lex
Lex

Reputation: 7194

You didn't use the AngularJS-UI bootstrap directives. Here is a working sample based on what you have.

Javascript

angular.module('app', ['ui.bootstrap'])
    .controller('ctrl', function($scope) {
        $scope.activeTab = "sqTab";
        $scope.next = function() {
            $scope.activeTab = "psTab";
        }
    });

HTML

<div ng-app="app" ng-controller="ctrl">
    <form class="tab-form-demo">
        <uib-tabset active="activeTab">
            <uib-tab index="'sqTab'" heading="tab1">
                Here is some content on Tab 1
            </uib-tab>
            <uib-tab index="'psTab'" heading="tab2">
                Here is some different content on Tab 2
            </uib-tab>
        </uib-tabset>
        <button ng-click="next()">next</button>
    </form>
</div>

Notice that when using a string index you have to put quotes around it. Also notice that the uib- version of all the bootstrap elements need to be used. Here is a working JSFiddle using the above code.

Upvotes: 2

Related Questions