5

I have this dropdown in my page

<select 
    ng-options="col.col_id as col.col_name for col in meta_data.x_cols"
    ng-model="obj.x">
</select>

Since the model is set to obj.x, I can access it using $scope.obj.x in any $scope function.

Naturally, it gives the value of the selected option. Is there any way by which I can get selected text as well? for e.g. bind obj.x to and obj.x_text to the text of selected option.

1
  • 2
    just drop the 'as' ng-options="col.col_name for col in meta_data.x_cols". then your model will be the whole object. Here is an example - jsfiddle.net/devitate/LKeQz Commented Aug 11, 2014 at 5:59

2 Answers 2

9

If you bind col and not col.col_id:

<select 
    ng-options="col as col.col_name for col in meta_data.x_cols track by col.col_id"
    ng-model="obj.x">
</select>

you will be able to access both col_id and col_name from $scope.obj.x:

$scope.obj.x.col_id
$scope.obj.x.col_name
Sign up to request clarification or add additional context in comments.

5 Comments

Hey, it solved that problem but created new problem. When I change the model, it doesn't update the view. I think because now its an object, equality would fail, since ({} != {}).
Can you share a plunkr illustrating the behaviour?
Here's a fiddle jsfiddle.net/x8rq2pda/3. See how second select is not getting assigned value.
using angular 1.2 and above, you can use the track by, see jsfiddle.net/qomn86k3
Thanks man, you're awesome. I wish I could re-accept the answer. :)
0

Why not use ng-repeat on options tag..

for e.g

<select 
    ng-options="col.col_id as col.col_name for col in meta_data.x_cols"
    ng-model="obj.x">

    <option
      ng-repeat="col in meta_data.x_cols"
      value="{{col.id}}"
    >{{col.name}}</option>

</select>

1 Comment

I don't like this approach for large lists as the rendering is much slower in IE 11/Edge (I am sure other previous versions of IE too)

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.