Question

I have an select field with an ng-model attribute in a tab within ui-bootstrap's tabset. There is also a button on the tab. On click of the button I would like to get the selected value in the model. I tried using

<select ... ng-model="selectedOption"></select>
<button ng-click="buttonClick()">Click</button>

and then in the controller

$scope.buttonClick = function() {
  //try to access $scope.selectedOption
}

But that does not seem to contain the value. I tried looking into the $scope variable and it seems to contain the selectedOption inside something called $$childTail

Is there any other way to access the selectedOption value or should I change the structure of my view?

I have a Plunker here of what I'm trying to do.

Was it helpful?

Solution

Both Mathew Berg's and Bumblebee Man's answers should work but they do not explain what's happening.

Okay basically it goes down like this:

The tabset directive that you are using does transclusion so the selectedOption is actually in an inner scope(tabset's scope), not in your TabsDemoCtrl's cope. This answer explains what transclusion does, and how you can access an transcluded model.

Transclusion makes shallow copies of your models, so even if you init selected option like $scope.selectedOption = "5"; in your TabsDemoCtrl, your select will show 5 as selected at the begining but changes will not be reflected to your TabsDemoCtrl controller's scope because in the tabset's child scope 5 is just copied, and the one being updated is in the tabset's scope not your scope.

You can also use an object for your select's model. Since the transclusion creates a shallow copy, objects/arrays/functions are copied by reference and variables are copied by value. This is also why you can access your TabsDemoCtrl's button click from the inner scope.

updated plnkr with another alternative solution(the object version) :

created an object in your controller

$scope.selection = {};

and used in model like this

ng-model="selection.option"

http://plnkr.co/edit/5sI0arorV9dULzaDxRra?p=preview

OTHER TIPS

Angular ui tab/tabset directive create new scopes, so in order to access the parent scope (What you're trying to do) just attach $parent

<select name="selectedCampaign" ng-model="$parent.selectedOption" ng-options="option for option in options"></select>

Updated plunkr: http://plnkr.co/edit/BgMMn4tJRWm72ZXeQG3N

Edit: Apologies, I misread the question, can't you just do this?

<select ... ng-model="selectedOption"></select>
<button ng-click="buttonClick(selectedOption)">Click</button>

$scope.buttonClick = function(selectedOption) {
  selectedOption.whatever...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top