我是AngularJS
的初学者,目前在尝试将数据绑定到select
代码时遇到问题
我想做什么
edit
链接api
)selected
以下是我的代码
#in the HTML page
<select ng-model="FormData.name"
ng-options="n.name for n in names"
class="form-control input-lg no-border-radius" required>
</select>
#in my service I have defined the `names` array
names: [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}]
#this is what I do in initial form loading
$scope.name = <service name>.names;
$scope.FormData.name = $scope.names[0];
因此,我将值1
或2
保存在数据库中并将其恢复。如果GET
请求成功,我会
$scope.FormData = data; #data is the object form the server
所以问题是,当我这样做时,所有值都正确地设置在窗体中,除了
select tags
如何根据服务器请求为select标签设置选定值。
var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];
$scope.names =names;
$scope.FormData = {};
$scope.FormData.name = $scope.names[1];
在以下数组中,我不是按索引选择项目,而是如何按name
或value
选择项目,例如
$scope.FormData.name = $scope.names['2']; #will select the {name: 'Batman', val: '2'}
答案 0 :(得分:0)
无需将值加载为字符串,请尝试加载为INT
:
names: [{name: 'Superman', val: parseInt('1')},{name: 'Batman', val: parseInt('2')}]
由于你有ng选项只从数组中获取名称,因此他们的id成为他们的索引。
您也可以尝试:
<select ng-model="FormData.name"
ng-options="n.val as n.name for n in names"
class="form-control input-lg no-border-radius" ng-model="FormData.val" required>
</select>
这样索引就成了字符串&#39; 1&#39;。
修改强>
忘了ng模型。
答案 1 :(得分:0)
使用给定代码找到的问题很少:
1)初始化$ scope.name而不是$ scope.names
2)访问$ scope.FormData.name而不初始化$ scope.FormData
请在下方找到更正后的代码:
var names= [{name: 'Superman', val: '1'},{name: 'Batman', val: '2'}];
$scope.names =names;
$scope.FormData = {};
$scope.FormData.name = $scope.names[0];
答案 2 :(得分:0)
根据问题的新简化版本回答: 下面的代码可用于根据名称
初始化下拉列表var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];
$scope.names =names;
$scope.FormData = {};
/*Iterating through the array and finding the required object based on the 'name' field*/
var isSuccess = false; //variable to prevent the iteration once the match is found
angular.forEach(names, function(name){
if(!isSuccess && name.name === 'Batman'){
$scope.FormData.name = name;
isSuccess = true;
}
});
};
请检查这是否有帮助!