Angularjs加入动态形成各种形式的字段 [英] Angularjs adding dynamically form fields in various forms

查看:108
本文介绍了Angularjs加入动态形成各种形式的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用纳克重复我创造一堆形式在它的值。随着每种形式也有按键将行添加到新的领域的具体形式。 code是低于

Using ng-repeat I am creating bunch of forms with values in it. With each form there is also button to add rows to that particular form with new fields. Code is below

HTML

<form name="{{form.name}}"
      ng-repeat="form in forms">          
  <h2>{{form.name}}</h2>
  <div ng-repeat="cont in form.contacts">
          <input type="text" class="xdTextBox" ng-model="cont.ac"/>
          <input type="text" class="xdTextBox" ng-model="cont.a_number"/>
          <input type="text" class="xdTextBox" ng-model="cont.p_id"/>             
  </div>
  <button ng-click="submit(form)">Submit</button>
  <button ng-click="addFields(form)">Add</button>
  <hr>
</form>

使用Javascript:

Javascript:

var app = angular.module('plunker', []);
    app.controller('MainCtrl', function($scope) {

        $scope.forms = [{
          "name" : "form1", "ac": 251, "a_number": "7933", "p_id": 33
        }, {
           "name": "form2", "ac": 252, "a_number": "7933", "p_id": 4
        }, {
           "name": "form3", "ac": 253, "a_number": "7362", "p_id": 3
        }];


        $scope.addFields = function (form) {        
            form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
        }

        $scope.submit = function(form){
          console.log(form.contacts);
        }
    });

这是行不通的。下面是它的plunker:
<一href=\"http://plnkr.co/edit/THdtLgkwKrV7imqZGjL2?p=$p$pview\">http://plnkr.co/edit/THdtLgkwKrV7imqZGjL2?p=$p$pview

这是怎么回事应该看(区别是从数据库接收到的数据对象是比这previously问的问题略有不同):
<一href=\"http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=$p$pview\">http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=$p$pview
请让我知道问题出在哪里。谢谢

This is how it should be looking(Difference is data object received from db is little different than this previously asked question): http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=preview Please let me know where the problem is. Thanks

推荐答案

addFields 方法的问题。只需添加为当 form.contacts情况下是未定义并将其设置为空数组。或者让每个窗体项目开始与联系人键设置为空数组。

Your addFields method is the problem. Just add a case for when form.contacts is undefined and set it to empty array. Or make each form item start with a contacts key set to an empty array.

$scope.addFields = function (form) {
  if(typeof form.contacts === 'undefined') {
    form.contacts = [];
  }
  form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
}

工程与您普拉克这个叉这种变化。

角也有确定何时事情是不确定的,你可能想使用,虽然我不知道它是否真的有什么差别的辅助功能。

Angular also has a helper function for determining when something is undefined you might want to use though I do not know if it really makes any difference.

angular.isUndefined(form.contacts)

这篇关于Angularjs加入动态形成各种形式的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆