Search code examples
angularjsangularjs-ng-repeat

How to make angularJS ng-model work with objects in select elements?


I have a problem with ng-model on a select element when passing an object from option elements. So, imagine we have an array of columns from a table called columns (the table's definition) and we'd like to creat some filters upon this definition

var columns = [
  {name: 'Account ID',    type: 'numeric'},
  {name: 'Full name',     type: 'text'},
  {name: 'Date of birth', type: 'date'},
  {name: 'Active',        type: 'boolean'}
  // and so on
];

var filters = [{}];

HTML:

<div class="form-field" ng-repeat="filter in filters">
  <select ng-model="filter">
    <option value="" disabled>Choose filter</option>
    <option ng-repeat="column in columns" ng-value="column">{{column.name}}</option>
  </select>
  <input type="text" ng-model="filter.value">
</div>

As you can see, I'd like that filter to get the value of column and to add specific data in it, so at a certain moment, my filter could be like:

[
  {name: 'Account ID', type: 'numeric', value: 123},
  {name: 'Active', type: 'boolean', value: 'Yes'}
]

Anyway, I'm not sure this is the way of doing this, but I'd like to know how can I achieve this behavior, withour writing to much js code in the controller.

I did some workaround to get this done using ng-change, passing the filter and the column.name, find the column in the columns array, get the type property, update the filter, but I really think that there is a simpler answer to this.


Solution

  • You can use ng-options to bind the selected object to a model:

    <div class="form-field" ng-repeat="filter in filters">
       <select ng-options="column.name for column in columns" ng-model="filter.value">
             <option value="" disabled>Choose filter</option>
       </select>
    
       <input type="text" ng-model="filter.value.name">
    </div>
    

    Plunker

    Updated answer:

    <div class="form-field" ng-repeat="filter in filters">
       <select ng-options="column.name for column in columns" ng-model="filters[$index]">
         <option value="" disabled>Choose filter</option>
       </select>
    
       <input type="text" ng-model="filters[$index].name">
    </div>