Reputation: 2027
I have an angular app that contains a form, which has a select. I can choose one of the selects, and its updated in the model perfectly. But the next time i go in the form its suppose to be "pre filled" as the data already exists. And all the data is filled ok, but angular doesn't seem to recognise that the value of the model corresponds to the value of the select.
html/angular:
<select ng-model="userData.country"
ng-options="country as country.name for country in countries">
</select>
data
[
{"iso":"DK","name":"Danmark"},
{"iso":"DE","name":"Germany"}
]
The wanted behaviour is that once I set this data to userData.country, that the form will come pre-selected with the correct country that the user chose in the previous form.
Upvotes: 1
Views: 267
Reputation: 466
In case you want to save the whole object instead of just the iso code here is an example:
JS File:
$scope.countries = [{
iso: "DK",
name: "Danmark"
}, {
iso: "DE",
name: "Germany"
}];
$scope.userData = {};
$scope.userData.country = $scope.countries[0];
HTML File:
<select ng-model="userData.country" ng-options="country as country.name for country in countries"></select>
I would suggest storing the whole object, that you wouldn't have to search the country array later if you needed the name and only had the ISO code.
Upvotes: 1
Reputation: 801
In Your HTML you need to add country.iso instead of country
<select ng-model="userData.country"
ng-options="country.iso as country.name for country in countries">
</select>
And in your controller
$scope.userData = {"country":"DK"}; // this can be filled with prefilled data. which can be fetched from db or stored in a service
Upvotes: 1
Reputation: 88
Try to change your html/angular to
<select ng-model="country"
ng-options="country.name for country in countries" ng-change="countryChanged(country)">
</select>
and your controller:
$scope.countryChanged = function(country){
$scope.userData.country = country
}
Upvotes: 0
Reputation: 6543
You probably are not filling the form in the Angular Way.
To do this, you should set the model (and the form will be pre-filled):
In your controller:
$scope.countries = [
{"iso":"DK","name":"Danmark"},
{"iso":"DE","name":"Germany"},
{"iso":"PT","name":"Portugal"},
{"iso":"CN","name":"Canada"}
];
$scope.userData = {};
$scope.userData.country = $scope.countries[3];
Upvotes: 0