2

I have an array of objects:

$scope.allCategories = [{'name': 'cat1', 'description: ... },
                        {'name': 'cat2', 'description: ... }, 
                        {...}];

I was previously using:

<select ng-model="mycategory" ng-change="test()">
    <option ng-repeat="category in allCategories">{{ category.name }}</option>
</select>

Which worked fine, but it's not the "Angular way". So I have changed it to:

<select ng-model="mycategory" ng-change="test()" ng-options="category.name for category in allCategories track by category.name"></select>

Which builds this correct html:

<select ...>
<option value="cat1" label="cat1">cat1</option>
<option value="cat2" label="cat2">cat2</option>
...
</select>

However in my test():

// called whenever select changes
$scope.test = function() {
    console.log($scope.mycategory);   
}

$scope.mycategory prints out the object {'name': 'cat1', 'description: ... } instead of the string value. The previous version with ng-repeat would give me the string value, so this threw me off.

Is there a way to get the string value automatically without doing $scope.mycategory = $scope.mycategory['name']; inside my test()?

rublex
  • 1,893
  • 5
  • 27
  • 45
  • 1
    Use `category.name as category.name for category in allCategories track by category.name` instead. See [the documentation](https://docs.angularjs.org/api/ng/directive/ngOptions). – Blackhole Jun 06 '15 at 20:57
  • 1
    I think this is a duplicate to this issue. Hope this helps. http://stackoverflow.com/questions/12139152/how-to-set-the-value-property-in-angularjs-ng-options/30291578#30291578 – Jeffrey A. Gochin Jun 07 '15 at 05:25

2 Answers2

1

Here is code :

<select ng-model="correctlySelected"
    ng-options="category.name as category.name for category in allCategories">
</select>
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Hari Inukollu
  • 179
  • 2
  • 10
0

To get exact selected value change your test method as follows:

$scope.test = function() {
console.log($scope.mycategory);}

change your html part as

<select ng-model="mycategory" ng-change="test()" ng-options="category.name for category in allCategories"></select>
ReeganLourduraj
  • 863
  • 6
  • 9