1

I'm having trouble dynamically capturing form inputs in angular. I have a form that takes several inputs for a resource. Each resource has many sections, and each section has many links. I've been able to get the functionality to work for a user to dynamically add/remove sections and links, but when it comes to actually capturing that with ng-model I can't seem to get it.

Based on this stackoverflow post, I thought I could do something like the first answer, ng-model="newResourceForm.sections[section.title]", but that doesn't seem to be working for me (it says that it is undefined)

Here is a link to a plunkr that I made for it:

Community
  • 1
  • 1
Kyle Giard-Chase
  • 243
  • 3
  • 15

2 Answers2

0

Looks like the problem in your code is that you are binding your variables to

newResourceForm.sections

but you are creating new sections inside an array named sections without a title property.

Using ng-model="newResourceForm.sections[section.title]" works but section.title is undefined. The result is your newResourceForm.sections object contains just one section named undefined no matter how many objects you have in your sections array.

Pedro Affonso
  • 1,656
  • 15
  • 26
0

The way you're adding/editing sections is a little off. It's hard to say without looking at your controller code, but I think this is part of the issue:

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

and it should look more like

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

I made a really minimal working version of what I think you were going for, feel free to try it out! (you just have to change the location of 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>
Brendan W
  • 3,303
  • 3
  • 18
  • 37