Binding both value and text in select dropdown in angular.js
Asked Answered
D

2

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.

Deity answered 11/8, 2014 at 5:46 Comment(1)
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/LKeQzCampinas
O
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
Overpass answered 11/8, 2014 at 5:52 Comment(5)
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 ({} != {}).Deity
Can you share a plunkr illustrating the behaviour?Overpass
Here's a fiddle jsfiddle.net/x8rq2pda/3. See how second select is not getting assigned value.Deity
using angular 1.2 and above, you can use the track by, see jsfiddle.net/qomn86k3Overpass
Thanks man, you're awesome. I wish I could re-accept the answer. :)Deity
J
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>
Janae answered 11/8, 2014 at 5:53 Comment(1)
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)Cioffred

© 2022 - 2024 — McMap. All rights reserved.