我还算是初学者 AngularJS
,并试图将数据绑定到当前时遇到问题,我的选择
标签
我想要做什么。
用户点击修改
链接现有对象加载到页面(通过后端 API
)对象的值应选
在drpodown 以下是我的code
#in HTML页面<选择NG模型=FormData.name NG-选项=n.name在名称N 类=的形式控制输入-LG无边框半径要求>< /选择>#in我的服务,我已经定义了`names`阵列名称:[{名称:'超人',VAL:'1'},{名称:'蝙蝠侠',VAL:'2'}]#这个是我在最初的形式加载办$ scope.name =<服务名称> .names;$ scope.FormData.name = $ scope.names [0];
所以我保存值 1
或 2
在数据库中,并得到它回来。如果 GET
请求成功,我
$ scope.FormData =数据; #DATA是对象形成服务器
所以,问题是,我这样做的时候,所有的值的形式正确地设置除外选择标记
如何设置选定值我取决于服务器的要求选择标签。
VAR名= [{名称:'超人',VAL:'1'},{名称:'蝙蝠侠',VAL:'2'}];$ scope.names =名称;$ scope.FormData = {};$ scope.FormData.name = $ scope.names [1];
在下面的阵列,而不是通过索引选择项目,如何选择通过名称
或数值的项目
,像
$ scope.FormData.name = $ scope.names ['2']; #will选择{名称:'蝙蝠侠',VAL:'2'}
解决方案
根据问题的新的简化版本答案: 低于code可用于基于名称初始化下拉
VAR名= [{名称:'超人',VAL:'1'},{名称:'蝙蝠侠',VAL:'2'}];$ scope.names =名称;$ scope.FormData = {};/ *通过阵列迭代和寻找基于姓名字段*所需的对象/VAR isSuccess = FALSE; //变量prevent一次比赛迭代发现angular.forEach(名称,功能(名称){ 如果(isSuccess&安培;!&安培; name.name ==='蝙蝠侠'){ $ scope.FormData.name =名称; isSuccess =真;}});};
请检查是否这有助于!
I'm fairly a beginner for AngularJS
and currently having problems when trying to bind data to my select
tag
What I want to do
user clicks theedit
link
existing object loads to the page (via back end api
)
object value should be selected
in the drpodown
Following is my code
#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];
So I save the value 1
or 2
in the DB and getting it back. If the GET
request is successful, I do
$scope.FormData = data; #data is the object form the server
So the problem is, when I do this, all the values are setting in the form correctly except
select tags
How can I set selected values for my select tags depending on the server request.
var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];
$scope.names =names;
$scope.FormData = {};
$scope.FormData.name = $scope.names[1];
In the following array, instead of selecting the item by index, how can I select the item by name
or the value
, like
$scope.FormData.name = $scope.names['2']; #will select the {name: 'Batman', val: '2'}
解决方案
Answer based on the new simplified version of the question : Below code can be used to initialise the dropdown based on name
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;
}
});
};
Kindly check if this helps!