Tabset $rootScope scope not updating

2019-02-27 12:50发布

问题:

I've a screen in below structure.

UserExperienceScreen
   <tabset>    
       tab 1 - <controller> <form> - input fields - form submit - go to tab2    
       tab 2 - <controller1> <form> - populate other details based on the tab1 information - form submit - go to tab3
       tab 3 - ....
   </tabset>

I'm not able to get access the input field values entered in first tab from second tab. If i move the code out of the tabset it works fine. given plunker below.

what am i doing wrong? it would be greatful if the screen have only one controller and share model across tabs.

Plunker Code: http://plnkr.co/edit/MZdELPvnaFp9pRvgJHVd?p=preview

回答1:

It is not advisable to pollute the $rootScope like this, instead you can either share a common servce data across your controllers or simply use one controller for all your tabs, such as the following:

[1] Share a common service data across your controllers:

DEMO

JAVASCRIPT

angular.module('plunker', ['ui.bootstrap'])

.service('Common', function() {
  this.tabData = {};
})

.controller('SampleController', function($scope, Common) {
  $scope.tabData = Common.tabData;
})

.controller("SampleTab2Controller", function($scope, Common) {
  $scope.tabData = Common.tabData;
});

HTML

<tabset ng-init="steps={step1:true, step2:false}">

   <tab heading="Step 1" active="steps.step1">
    <div data-ng-controller="SampleController">      
      <form data-ng-submit="submitTab1()">
           <label>Input Text</label>
         <input type="text" ng-model="tabData.text" required >
          <button type="submit">Next</button>
      </form>
    </div>    
    </tab>

    <tab heading="Step 2" active="steps.step2">
    <div data-ng-controller="SampleTab2Controller">
      <form name="step2">
         <p>Text from Tab1</p>
        <input type="text" ng-model="tabData.text"  >
      </form>
      </div>
    </tab>

  </tabset>

[2] Use one controller for all your tabs

DEMO

JAVASCRIPT

angular.module('plunker', ['ui.bootstrap'])

.controller('TabController', function($scope) {

});

HTML

  <tabset ng-init="steps={step1:true, step2:false}"
    ng-controller="TabController">

   <tab heading="Step 1" active="steps.step1">
    <div>      
      <form data-ng-submit="submitTab1()">
           <label>Input Text</label>
         <input type="text" ng-model="tabText" required >
          <button type="submit">Next</button>
      </form>
    </div>    
    </tab>

    <tab heading="Step 2" active="steps.step2">
    <div>
      <form name="step2">
         <p>Text from Tab1</p>
        <input type="text" ng-model="tabText"  >
      </form>
      </div>
    </tab>

  </tabset>