0

Im a newbie in angular, trying to learn the language.

Got the following code: http://plnkr.co/edit/fuVb0mzhmDCKr1xKp7Rn?p=preview

Have a tab:

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider.when
        ('/jobs', {templateUrl: 'jobs-partial.html',   controller: JobsCtrl  }).
      when
        ('/invoices', {templateUrl: 'invoices-partial.html',   controller: InvoicesCtrl }).
      when
        ('/payments', {templateUrl: 'payments-partial.html',   controller: PaymentsCtrl }).
      otherwise({redirectTo: '/jobs'});

      // make this demo work in plunker
      $locationProvider.html5Mode(false);
}]);

I would like to be able to access the selected tab from one the panel. How can I send parameters to the tab controllers?

1

2 Answers 2

2

Create a service that will set a value and return it:

.service('shared', function() {

  var myValue;

  return {
    setValue: function(value) {
      myValue = value;
    },
    getValue: function() {
      return myValue;
    }
  }
});

Then inject it into both your controllers:

.controller('Ctrl1', ['shared', function(shared)......

.controller('Ctrl2', ['shared', function(shared)......

And then set the value from Ctrl1:

shared.setValue('somevalue');

And in Ctrl2 you can just retrieve the value:

var mySharedValue = shared.getValue();
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a Service or Factory, inject that in to your TabsCtrl, save the currentTab state in that service in ng-click. Inject the same service in your Page controllers like JobsCtrl

app.factory('MyService',function(){

  var currentTab ;

  return {

      setCurrentTab : function(tab){
        currentTab = tab;
      },

      getCurrentTab : function(tab){
        return currentTab;
      }

  };

});

Update your TabsCtrl like below

function TabsCtrl($scope, $location, MyService) {
  // removing other code for brevity
  $scope.selectedTab = $scope.tabs[0];
  // saving the default tab state
  MyService.setCurrentTab($scope.tabs[0]);

  $scope.setSelectedTab = function(tab) {
    $scope.selectedTab = tab;
    // saving currentTab state on every click
    MyService.setCurrentTab(tab);
  }

}

In your JobsCtrl, inject the same MyService and retrieve the cached tab state like below

function JobsCtrl($scope, MyService) {
  var currentTab = MyService.getCurrentTab();
  alert(currentTab.label);
}

Here's an updated Plunker with the above changes.

1 Comment

Both Answers are right. I accepted yours as the right answer as you kept it relevant to the scenario "tabs" and you even went a step further an edited the Plunker. *Thumbs Up!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.