javascript - 将 ng-model 保存在数组中并使用循环 AngularJs 设置值
问题描述
设想
我有一个场景,我将解析文档,然后我将获得键和值格式的 JSON 输出,在键中它将包含文档的标题,值将包含标题的相应部分。现在我想将值绑定到 ng-model (表单中的文本框),我有 100 多个文本框,我可能会从文档中得到不同的标题,如果我得到不同的标题,我想用 or 条件绑定到 ng-model像下面的代码。
要求
我喜欢将我所有的 ng-model 名称存储到数组中,例如:
var array = [$scope.FirstNgModel,$scope.SecondNgModel,$scope.ThirdNgModel,$scope.FourthNgModel,$scope.FifthNgModel]
然后我将阅读完全匹配的内容并进行映射。
当前代码如下
$.ajax(settings).done(function (response) {
var docparsed = JSON.parse(response);
//angular.forEach($scope.ModelMaping, function (obj) {
angular.forEach(docparsed, function (obj) {
//var ModelVal = obj.value;
//var val = docparsed.find(x => x.key.toLocaleLowerCase() === ModelVal.toLocaleLowerCase())
//obj.key = val.value;
if (obj.key.toLocaleLowerCase() == "first") {
$scope.FirstNgModel = obj.value;
}
if (obj.key.toLocaleLowerCase() == "second") {
$scope.SecondNgModel = obj.value;
}
if (obj.key.toLocaleLowerCase() == "third") {
$scope.ThirdNgModel = obj.value;
}
if (obj.key.toLocaleLowerCase() == "fourth") {
$scope.FourthNgModel = obj.value;
}
if ((obj.key.toLocaleLowerCase() == "fifth") || (obj.key.toLocaleLowerCase() == "sixth")) {
$scope.FifthNgModel = obj.value;
}
});
解决方案
使用 AngularJS 框架,使用$http
服务:
$http.get(url)
.then(function(response) {
$scope.data = response.data;
}).catch(function(error) {
console.log(error);
});
无需使用jQuery.ajax
.
在 HTML 中,使用ng-repeat
指令:
<div ng-repeat="(key, value) in data">
{{key}}
<input type="text" ng-model="data[key]">
</div>
这将自动显示data
对象中的所有 100 多个条目。
要发布数据:
$http.post(url, $scope.data);
推荐阅读
- c# - 如何编译我的 Hello World 程序?
- react-native-android - 不使用 Firebase 时为 Android GoogleSignIn 生成 google-services.json
- python - 在 Django 中创建唯一的会话 URL
- kotlin-exposed - 在 Exposed 中选择查询作为 where 条件
- forms - 如何以谷歌形式将默认日期设置为今天?
- python - django manytomany postgresql
- python - 如何在 Python 中使用 Selenium 从 https://www.amazon.in/ 中的下拉列表框中选择书籍选项?
- reactjs - 样式化的组件 选定的导航项
- c# - 尝试使用带参数的 KeyPress,但不知道如何正确传递参数
- javascript - 如何根据条件调用javascript中的函数