Reputation: 47
Once I use ng-options
for a select I am unable to get dafault selection to work on nested json objects.
once I have a bit more complicated json and the select should handle a child object my select does not default select the proper value.
Given test = {"id":3,"title":"Test","product":{"id":4,"name":"Test1"}}
as my ng-model test.product
and
[{
"id": 4,
"name": "Test1"
}, {
"id": 5,
"name": "Test2"
}]
as my selection option. (see http://embed.plnkr.co/mpnislw77UBSEdHl4UKN/) I seem to be unable to figure out how to facilitate default selection.
If you use track by item.id it works - http://embed.plnkr.co/mpnislw77UBSEdHl4UKN. The marked answer was not very obious since the ng-model is nested in iself. but it contains the correct information.
Upvotes: 0
Views: 795
Reputation: 3177
This is how to select with ngOptions and setting a default value
Example
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
};
}]);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="defaultValueSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id"
ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
</body>
</html>
Upvotes: 0
Reputation: 19
try this, hope it will help
<option value="" ng-if="false"></option>
Upvotes: 0
Reputation: 23869
The only problem with your code is that you've assigned a new object to $scope.test.product
and you're using it as the ng-model
of the dropdown.
This makes AngularJS unable to find it inside the possible values, which are $scope.testarray
. AngularJS will compare two objects by their reference, which you broke when you assigned a new object to $scope.test.product
.
To make it working, change $scope.test
as follows:
$scope.test = {
"id": 3,
"title": "Test",
"product": $scope.testarray[1]
}
Upvotes: 1