[英]How to display the selected value in select option field from the json object fetched form server angularjs
[英]Angularjs select field does not display selected
我有一個像這樣的角度指令:
'use strict';
angular.module('countrySelect', [])
.directive('countrySelect', ['$parse', function($parse) {
var countries = [
{ code: "af", name: "Afghanistan" },
{ code: "ax", name: "Åland Islands" },
{ code: "al", name: "Albania" },
{ code: "dz", name: "Algeria" },
];
return {
template: '<select ng-options="c.code as c.name for c in countries">',
replace: true,
link: function(scope, elem, attrs) {
scope.countries = countries;
if (!!attrs.ngModel) {
var assignCountry = $parse(attrs.ngModel);
elem.bind('change', function(e) {
assignCountry(elem.val());
});
scope.$watch(attrs.ngModel, function(country) {
elem.val(country);
});
}
}
}
}]);
並且模板中的選擇字段如下:
<div country-select ng-model="citizenship"></div>
我可以選擇一個選項,模型會按照預期更新國家/地區代碼,但國家/地區名稱不會出現在選擇字段中,除非我再次選擇它。
換句話說,這個過程就是如此
如何在選擇時讓選擇字段顯示國家/地區名稱?
由於您正在使用replace: true
原始ng-model="citizenship"
最終會以select元素結束,因此您不需要處理選擇更改事件以更新ngModel
,它已經綁定到選擇框。 所以你的指令看起來應該是這樣的:
angular.module('countrySelect', [])
.directive('countrySelect', [function() {
var countries = [
{ code: "af", name: "Afghanistan" },
{ code: "ax", name: "Åland Islands" },
{ code: "al", name: "Albania" },
{ code: "dz", name: "Algeria" },
];
return {
template: '<select ng-options="c.code as c.name for c in countries"></select>',
replace: true,
link: function(scope, elem, attrs) {
scope.countries = countries;
}
}
}]);
您可能希望使用$apply()
來“強制更新”視圖。 http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.