I am using angular's ng-options to populate the html with the names of people. I want it to pre-select the value that I have set as the ng-model (registrantSelected). But for some reason, it won't do so.
I have looked up various different documentations for ng-options and looked at a bunch of other stack overflow posts about ng-options, but I can't seem to figure out what I am doing wrong.
Code can be found in this plunker or below:
Javascript:
angular.module('app', [])
.controller("MainController", ["$scope", function($scope) {
$scope.paidDuesCompanyPeople = [{
"FirstName": "Person",
"LastName": "One",
"MemberType": {
"IsMember": false,
"Name": "Non-member"
}
}, {
"FirstName": "Second",
"LastName": "Person",
"MemberType": {
"IsMember": true,
"Name": "Member"
}
}, {
"FirstName": "Three",
"LastName": "People",
"MemberType": {
"IsMember": false,
"Name": "Non-member"
}
}];
$scope.registrantSelected = {
"FirstName": "Person",
"LastName": "One",
"MemberType": {
"IsMember": false,
"Name": "Non-member"
}
};
}]);
HTML:
<div ng-app="app" ng-controller="MainController">
<div class="col-xs-12 col-sm-5">
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-6 control-label">Registration for</label>
<div class="col-sm-6">
<select class="form-control" ng-model="registrantSelected" ng-options="person.FirstName + ' ' + person.LastName for person in paidDuesCompanyPeople">
</select>
</div>
</div>
</form>
</div>
{{registrantSelected}}
</div>
Thank you for any help you can give!
You could do this thing by introducing track by
in your ng-options
but for having track by
you should have unique property over there. I'd highly recommnd you to add Id
property so that would make each record unique & you can track by the same. But for now just for demonstration you can track it by person.FirstName + person.Lastname
(you will have track by person.Id when you add id)
<select class="form-control"
ng-model="registrantSelected"
ng-options="person.FirstName + ' ' + person.LastName for person in paidDuesCompanyPeople track by person.FirstName + person.Lastname ">
</select>