[英]ng-select won't recognise the ng-model is a valid option and should be selected
我有一個角度應用程序,其中包含一個帶有選擇的表單。 我可以選擇其中之一,並在模型中完美地對其進行更新。 但是下一次我以它的形式應該被“預先填充”,因為數據已經存在。 並且所有數據都可以正常填充,但是角度似乎無法識別出模型的值與選擇的值相對應。
HTML /角:
<select ng-model="userData.country"
ng-options="country as country.name for country in countries">
</select>
數據
[
{"iso":"DK","name":"Danmark"},
{"iso":"DE","name":"Germany"}
]
所需的行為是,一旦將數據設置為userData.country,該表單將被預先選擇用戶在先前表單中選擇的正確國家/地區。
在您的HTML中,您需要添加country.iso而不是country
<select ng-model="userData.country"
ng-options="country.iso as country.name for country in countries">
</select>
而在您的控制器中
$scope.userData = {"country":"DK"}; // this can be filled with prefilled data. which can be fetched from db or stored in a service
如果您想保存整個對象而不是僅保存iso代碼,請參見以下示例:
JS文件:
$scope.countries = [{
iso: "DK",
name: "Danmark"
}, {
iso: "DE",
name: "Germany"
}];
$scope.userData = {};
$scope.userData.country = $scope.countries[0];
HTML檔案:
<select ng-model="userData.country" ng-options="country as country.name for country in countries"></select>
我建議存儲整個對象,如果您需要名稱並且僅具有ISO代碼,則以后不必搜索country數組。
您可能未按Angular Way填寫表格。
為此,您應該設置模型(表格將被預先填寫):
在您的控制器中:
$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];
嘗試將您的html / angular更改為
<select ng-model="country"
ng-options="country.name for country in countries" ng-change="countryChanged(country)">
</select>
和您的控制器:
$scope.countryChanged = function(country){
$scope.userData.country = country
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.