【问题标题】:AngularJS - Creating and retrieving dynamically created formsAngularJS - 创建和检索动态创建的表单
【发布时间】:2014-05-08 11:41:56
【问题描述】:

我有一个包含“属性”部分的表单。用户可以根据需要添加任意数量的属性:

HTML:

<h4>
   Attributes:
   <input type="button" value="+" id="new_obj_att_add" ng-click="addNewChoice()">
</h4>
<div class="form-group" ng-repeat="attribute in attributes">
    <input type="text" ng-model="att_name" placeholder="Attribute Name">
    <input type="text" ng-model="att_value" placeholder="Attribute Value">
    <hr>
</div>

JS:

$scope.attributes = [{id: 1}];
    $scope.addNewChoice = function() {
    var newItemNo = $scope.attributes.length+1;
    $scope.attributes.push({'id': newItemNo});
};

现在,该代码非常适合动态增长表单。但是,我需要将表单数据传回我的控制器。如您所见,每个属性都将具有相同的 ng-model,因此我无法从那里获取它。

1) 有没有办法使用每个属性的 ID(即 attr_name_1、attr_name_2)动态分配 ng-model 名称,然后在我的 AngularJS 公式中循环遍历这些元素并以这种方式收集值?

2) 如果我要在 AngularJS 中再次引用这些元素,我是否只是没有以正确的方式创建这些元素?

提前感谢您提供的任何帮助!

【问题讨论】:

    标签: forms angularjs dynamic


    【解决方案1】:

    您只需将其分配给ng-repeat 中的模型:

    <div class="form-group" ng-repeat="attribute in attributes">
        <input type="text" ng-model="attribute.att_name" placeholder="Attribute Name">
        <input type="text" ng-model="attribute.att_value" placeholder="Attribute Value">
        <hr>
    </div>
    

    然后这些值会自动分配给 attributes 集合中的正确模型。

    【讨论】:

    • 这是有道理的。我将如何在我的 JS 中引用它?假设我从 printAttributes(attributes) 的 HTML 调用一个函数,我不确定如何遍历该属性列表并获取名称/值。
    • 属性在$scope.attributes 中,您可以像添加新属性一样访问它们。对于循环,您可以使用angular.forEach
    • 啊,完美。非常感谢。
    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2017-01-31
    相关资源
    最近更新 更多