2014-03-28 32 views
0

我有一个表单,具有'属性'部分。用户可以根据他/她想要添加尽可能多的属性:AngularJS - 创建和检索动态创建的表单

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模型,所以我不能从那里获取它。

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

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

在此先感谢您的帮助!

回答

0

你必须把它分配给在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收藏。

+0

这很有道理。我如何在JS中引用它?假设我从printAttributes(attributes)的HTML调用一个函数,我不知道如何遍历该属性列表并获取名称/值。 – ev0lution37

+0

这些属性位于'$ scope.attributes'中,您可以按照与添加新属性完全相同的方式访问它们。对于循环,你可以使用'angular.forEach'。 –

+0

啊,完美。万分感谢。 – ev0lution37