如何使ng模型动态化?

时间:2018-10-03 10:04:30

标签: angularjs

我正在制作一个动态注册表格My dynamic form example。这些输入中写入的数据将稍后发送到某个API。

<div ng-repeat="item in CustomRegistrationForm" class="form-group text-field-para" style="margin: 10px">
     <input type="{{item.Type}}" id="{{'A'+$index}}" class="form-control" name="{{TmpName}}" ng-model="RegistationSubscriberData.User.CustomRegistrationForm[$index].Name">
</div>

CustomRegistration是这样制作的JSON:https://jsoneditoronline.org/?id=5396efadcf9d475a9fee6e558e8b807c。 按照我的逻辑,必须将ng-models设置为(以我为例):“ FirstName”,“ Email”,“ GSMnumber”,......但是它只是保存为ng-model中的最后一个字符串,位于{{ 3}}“名称”。我也尝试使用item.Name,但没有任何区别。另外,如果我尝试“ console.log(CustomRegistration [0] .Name)”,它可以正常工作并输出“ FirstName”

有人可以向我解释为什么在这种情况下,我的“类型”可以完美地(动态地)工作,但是ng-model无法与动态变量一起工作。这是我的第一个问题,因此,如果我有任何错误,请事先道歉。

1 个答案:

答案 0 :(得分:0)

您必须为 ng-model 创建数组,然后可以将其动态添加到该数组中,如下所示。

<div ng-app ng-controller="TestController">
    <div ng-repeat="item in CustomRegistrationForm" class="form-group text-field-para" style="margin: 10px">
         <input type="{{item.Type}}" id="{{'A'+$index}}" class="form-control" name="{{TmpName}}" ng-model="Users[item.Name]">
    </div>
    <p> {{Users}} </p>
</div>

在控制器中

function TesyController($scope) {

    $scope.RegistationSubscriberData = {};

        $scope.CustomRegistrationForm = [
  {
    "Label": "First name",
    "Name": "FirstName",
    "Type": "text",
    "Mandatory": true,
    "Length": 20,
    "showPlaceHolder": false,
    "Regex": "/^[a-z ,.'-]+$/i",
    "Validator": "",
    "requireRetypePassword": false,
    "strengthValidatorEnabled": false,
    "strengthComplexityLevel": false,
    "Format": ""
  },
  {
    "Label": "Email",
    "Name": "Email",
    "Type": "email",
    "Mandatory": true,
    "Length": "",
    "showPlaceHolder": false,
    "Regex": "",
    "Validator": false,
    "requireRetypePassword": false,
    "strengthValidatorEnabled": false,
    "strengthComplexityLevel": false,
    "Format": ""
  },
  {
    "Label": "Phone number (international format)",
    "Name": "GSMNumber",
    "Type": "text",
    "Mandatory": false,
    "Length": "",
    "showPlaceHolder": false,
    "Regex": "/^[a-z ,.'-]+$/i",
    "Validator": "",
    "requireRetypePassword": false,
    "strengthValidatorEnabled": false,
    "strengthComplexityLevel": false,
    "Format": ""
  },
  {
    "Label": "Password",
    "Name": "password",
    "Type": "password",
    "Mandatory": true,
    "Length": "",
    "showPlaceHolder": false,
    "Regex": "",
    "Validator": false,
    "requireRetypePassword": true,
    "strengthValidatorEnabled": true,
    "strengthComplexityLevel": false,
    "Format": ""
  }
]
}

作为参考,您可以参考下面的小提琴链接

fiddle fiddle 2

希望这会对您有所帮助。