Kyle Giard-Chase
Kyle Giard-Chase

Reputation: 243

Dynamically adding form fields within fields angular js

I have a form that is taking input from a user for a resource. Each resource has many sections and each section has many links. I have added the ability for the user to dynamically add section fields to the form, but I am lost when it comes to how to dynamically add link fields to each section.

My html currently looks like this:

    <div class="form-group" ng-repeat="section in sections">
      <input type='text', ng-model="newResourceForm.sections" name="" placeholder="Enter a section name">
      // ng-repeat over links here
      <button ng-click="removeSection()" ng-show="$last" Remove section
    <button type='button', ng-click="addSection()" Add another section>

The functionality that is dynamically adding the sections:

      $scope.sections = [{"id": 1}];
      $scope.addSection = function() {
        var newSectionNo = $scope.sections.length+1;
        $scope.sections.push({"id": newSectionNo});
      }
      $scope.removeSection = function() {
        var lastSection = $scope.sections.length-1;
        $scope.sections.splice(lastSection);
      }

My thought was that I would need to structure $scope.sections like so: $scope.sections = [{"id": 1, "links": [{"id": 1, "title": "", "url": ""}] But I'm new to Angular and don't quite know how to find the current section and push another link to it.

Upvotes: 0

Views: 680

Answers (1)

Anid Monsur
Anid Monsur

Reputation: 4538

You're on the right track. To find the current section and push another link to it, you need to take advantage of the variable you created with the ng-repeat. In your case, that's the section variable. You can pass that into functions as well, like this:

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

      <button type='button', ng-click='addLink(section)'>Add Link</button>

      <div ng-repeat='link in section.links'>
          <!-- Links here -->
      </div>

</div>

The new addLink function you'd create in the controller receives the section as a parameter, so you can directly modify it.

Upvotes: 1

Related Questions