如何根据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
但不工作...