【问题标题】:ng-model with dynamic form inputs具有动态表单输入的 ng-model
【发布时间】:2015-09-01 00:57:59
【问题描述】:

我无法以角度动态捕获表单输入。我有一个表格,它需要一个资源的多个输入。每个资源都有很多部分,每个部分都有很多链接。我已经能够让用户动态添加/删除部分和链接的功能,但是当涉及到使用 ng-model 实际捕获它时,我似乎无法获得它。

根据this stackoverflow 帖子,我认为我可以做类似第一个答案ng-model="newResourceForm.sections[section.title]" 的事情,但这似乎对我不起作用(它说它未定义)

这是我为它制作的plunkr 的链接:

【问题讨论】:

  • 嘿,你成功了吗?

标签: angularjs forms


【解决方案1】:

您的代码中的问题似乎是您将变量绑定到

newResourceForm.sections

但是您正在一个名为 sections 的数组中创建新部分,但没有标题属性。

使用 ng-model="newResourceForm.sections[section.title]" 有效,但 section.title 未定义。结果是您的newResourceForm.sections 对象只包含一个名为undefined 的部分,无论您的sections 数组中有多少对象。

【讨论】:

    【解决方案2】:

    您添加/编辑部分的方式有点偏离。不看你的控制器代码很难说,但我认为这是问题的一部分:

    <div ng-repeat="section in sections" class="form-group mt">
    

    它应该看起来更像

    <div ng-repeat="section in resource.sections" class="form-group mt">
    

    我做了一个我认为你想要的真正最小的工作版本,请随意尝试! (你只需要改变 angular.min.js 的位置)

    <html>
      <head>
        <script src="static/angular.min.js"></script>
        <script>
          angular.module('app', [])
          .controller('resourseCtrl', resourseCtrl);
    
          function resourseCtrl() {
            this.resource = {'sections': []};
            console.log('controller started');
            this.addSection = function() {
              this.resource.sections.push({});
            };
            this.removeSection = function() {
              this.resource.sections.splice(this.resource.sections.length - 1, 1);
            };
          }
        </script>
      </head>
      <body ng-app="app">
        <div ng-controller="resourseCtrl as resourseCtrl">
          <button ng-click="resourseCtrl.addSection()">add section</button>
          <button ng-click="resourseCtrl.removeSection()">remove section</button>
          <div ng-repeat="section in resourseCtrl.resource.sections">
            <p>name:<input text ng-model="section.name"></input></p>
            <p>title:<input text ng-model="section.title"></input></p>
            <p>description:<input text ng-model="section.description"></input></p>
          </div>
          {{ resourseCtrl.resource }}
        </div>
      </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2014-02-26
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      相关资源
      最近更新 更多