0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.