簡體   English   中英

如何通過角度下拉菜單中的ng-options設置所選選項?

[英]How to set selected option through ng-options in angular dropdown?

My code is like 

$scope.items = [{
"hospital_id":"hosp55121069e3cb0",
"hospital_name":"Sri Durga Clinic",
"locality":"Amasebail",
"speciality_name" : "Bone and Joint"
},
{
"hospital_id":"hosp55121069e3acd",
"hospital_name":"Apollo Clinic",
"locality":"Chennai",
"speciality_name" : "Cardiology"
}];
$scope.selectedHospital = null;
if(localStorage.getItem('selectedItem')) {
   $scope.selectedHospital = JSON.parse(localStorage.getItem('selectedItem'));

} else {
   $scope.selectedItem = $scope.items[1];
}
$scope.combined = function(item) {
     if (item.locality == undefined || item.locality == '') {
        return item.hospital_name;
     } else {
        return item.hospital_name + " " + item.speciality_name + " (" + item.locality + ")";
     }
}

$scope.update = function() {
        localStorage.setItem('selectedItem',  JSON.stringify($scope.selectedItem))

    }

當我通過localStorage值設置selectedItem時,它沒有選擇給定值。 但是,如果我通過$ scope.items [index]設置它,它就可以工作。

我的HTML如下:

<select ng-model="selectedItem" ng-change="update()" ng-options="combined(item) for item in items">           

ng-options ,您可以使用對象本身來設置selectedItem。 Angular會將相應的項目設置為選中狀態。 您無需提及特定值。

這就是為什么當您使用

$scope.selectedItem = $scope.items[index] 

有用。 因為對象綁定到選項的值。

通過localStorage進行設置時,

if(localStorage.getItem('selectedItem')) {
   $scope.selectedHospital = JSON.parse(localStorage.getItem('selectedItem'));

} else {
   $scope.selectedItem = $scope.items[1];
}

您實際上是在對對象進行字符串化並存儲它。 因此對象與之前的對象不同。 您需要遍歷項目列表並通過匹配該對象的屬性來查找。

還要注意,您將值設置為selectedHospital而不是selectedItem 但是在您的select您正在使用ng-model="selectedItem"作為模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM