如何根據ng-options中的ajax結果設置默認值?AngularJS ng-options Ajax默認選擇選項
<select ng-model="model.stuff" ng-options="o.name for o in options track by o.id"></select>
然後在我的控制器我有
$http.get("myurl").then(
// On Success
function(response) {
$scope.options = response.data;
},
// On Error
function(error) {
console.log("ERROR");
}
);
實例數據會是這樣
[
{
"id": 1,
"name": "Foo"
},
{
"id": 2,
"name": "Bar"
}
]
時,在我的控制器其他的東西被激活,這得到的是觸發,我的選擇列表中正確填寫,我所有的選擇。
但有時我需要在加載ajax數據後設置默認值。例如,我需要從我的數據數組中加載id 1
。
這並不意味着加載response.data[1]
這意味着我必須在response.data
之內進行搜索並尋找具有id: 1
的項目。這適用於這種方法
function getArrayIndex(key, source){
for (var i = 0; i < source.length; i++) {
if (source[i].id == key) {
return i;
}
}
}
這會告訴我,response.data[0]
有id: 1
所以我想用它作爲我的默認選擇的值時,AJAX加載我的數據。
我該如何做到這一點?
我讀過一些其他的問題,但我沒有什麼工作......我試過設置ng-init
與id
值和整個object
但不工作...