Leon Gaban Leon Gaban - 2 months ago 8
AngularJS Question

How to get changed value of a select in Angular - Without updating a global model?

I have several widgets which are generated from JSON data and an

ng-repeat
. Inside this widget is a select dropdown.

I'm able to call a function in my
Controller
with
ng-change
, however using
ng-model
on that select, changes the chosen value for all selects dropdowns in all the widgets.

How would I prevent this?

<div ng-repeat="item in widget.items" class="well col-md-6 col-lg-4">
<select ng-model="widget.chosenValue"
ng-change="widget.updateTag(item.item_id, widget.chosenValue)">

<option value="companies"
ng-selected="{{item.tag == 'companies'}}"
changed="companies">companies</option>

<option value="news"
ng-selected="{{item.tag == 'news'}}"
changed="news">news</option>

<option value="people"
ng-selected="{{item.tag == 'people'}}"
changed="people">people</option>

<option value="products"
ng-selected="{{item.tag == 'products'}}"
changed="products">products</option>
</select>
</div>


The model on the select:
ng-model="widget.chosenValue"


^ So choosing an option in the select will send the correct value into my
widget.updateTag
function, however it also changes the value in every other widget.

Is there a way to isolate the model scope to each widget?

Answer

If you want to know what they selected you should replace

ng-model="widget.chosenValue"
ng-change="widget.updateTag(item.item_id, widget.chosenValue)

with

ng-model="item.chosenValue"
ng-change="widget.updateTag(item)

This applies the chosenValue to each item in the list, so it would look like

<div ng-repeat="item in widget.items" class="well col-md-6 col-lg-4">
    <select ng-model="item.chosenValue"
            ng-change="widget.updateTag(item)">

Then in your updateTag function you can access

  • item.item_id
  • item.tag
  • item.chosenValue
Comments