首页 > 解决方案 > 将 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;
        }
    });

示例项目

标签: javascriptjqueryangularjsangularjs-ng-modelngmodel

解决方案


使用 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);

推荐阅读