red_white_code
red_white_code

Reputation: 111

ng-repeat with options doesn't return object as value

I have a loop "ng-repeat" inside of

<select ng-model="something"></select>

so that each option in a list is rendered as an

<option> 

inside of select block. My aim is to make "something" (which is a ng-model attached to select) to be equal to a selected object inside of the list. At this moment when I do "value="{{option}}" as a parameter of option, I have a JSON object as a String. But what I need is to get an object as an object. The code looks like this:

<select ng-model="something">
    <option ng-repeat="option in list" value="{{option}}">{{option.name}}</option>
</select>

The thing I want is easily done by using ng-options, but I need to add additional "style" parameters depending on option.anotherField to each

<option>

Upvotes: 4

Views: 3619

Answers (2)

Slava Utesinov
Slava Utesinov

Reputation: 13488

What about approach via temp proxy and it's relation with something variable with the help of ng-change($scope.setModel) directive:

(function(angular) {
  'use strict';
angular.module('app', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.list = [{name:'Tom',age:23},{name:'Max',age:33},{name:'Sam',age:43}];
    $scope.something = $scope.list[0];
    $scope.temp = $scope.something.name;    

    $scope.setModel = function(){
      for(var item of $scope.list)
        if(item.name == $scope.temp){
          $scope.something = item;
          break;
        }          
    }    
 }]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <div ng-app='app' ng-controller="ExampleController">
    <select ng-change='setModel()' ng-model='temp'>
      <option ng-repeat='option in list track by option.name' ng-attr-title='{{option.age}}'>{{option.name}}</option>
    </select>
    <div>something: {{something | json}}</div>
  </div>

Upvotes: 0

Yaser
Yaser

Reputation: 5719

You can use ng-value instead of value, which gives you the object you want:

<select ng-model="something">
    <option ng-repeat="option in list" ng-value="option">{{option.name}}</option>
</select>

Upvotes: 1

Related Questions