在 html 页面中,我有一个如下所示的选择,
<select>
<option value="GMT-12:00">(GMT -12:00) Eniwetok, Kwajalein</option>
<option value="GMT-11:00">(GMT -11:00) Midway Island, Samoa</option>
<option value="GMT-10:00">(GMT -10:00) Hawaii</option>
<option value="GMT-9:00">(GMT -9:00) Alaska</option>
...
</select>
然后我查询 REST API 并获取人员数据,例如,
person : {
language : "en_US",
timezone : "GMT-9:00"
...
}
问题:
在 AngularJS 应用程序中显示此页面时,如何将“(GMT -9:00) Alaska”设置为选定的?
最佳答案
您可以使用 ng-model
属性将 API json 响应绑定(bind)到您的 select
输入。
给定您的 HTML,我们会得到这个选择下拉列表,它将绑定(bind)到 person.timezone
.
<div ng-controller="MainController">
<select ng-model="person.timezone">
<option value="GMT-12:00">(GMT -12:00) Eniwetok, Kwajalein</option>
<option value="GMT-11:00">(GMT -11:00) Midway Island, Samoa</option>
<option value="GMT-10:00">(GMT -10:00) Hawaii</option>
<option value="GMT-9:00">(GMT -9:00) Alaska</option>
</select>
</div>
现在您需要 Controller 来实际调用 rest 服务并获取 person 对象:
function MainController($scope, $http) {
/* query rest api and retrive the person
this of course would be replaced with the url of your actual rest call */
$http({method: 'GET', url: 'rest_api_response.json'}).success(function(data, status, headers, config) {
$scope.person = data;
// dont apply if were in digest
if(!$scope.$$phase)
$scope.$apply();
}).
error(function(data, status, headers, config) {
console.log("error retriveing rest api response");
});
}
对于这个示例,我刚刚创建了一个名为
"rest_api_response.json"
的文件。包含您的回复{
"language" : "en_US",
"timezone" : "GMT-9:00"
}
Heres a plunker with the sample contained
关于Angularjs 设置选中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13796732/