jamcoder
jamcoder

Reputation: 569

Dynamically add new elements and add new sub-element on the selected element in angularjs

I am new to angularjs and I'm wondering on how to achieve this below sample.

Section 1 -- Sub Section 1 -- Sub Section 2 -- Sub Section 3

Section 2 -- Sub Section 1 -- Sub Section 2

Where user can add more Sections dynamically and from that section he/she can add more sub sections dynamically. Also, how can i get the index of specific element. Hope I explained it properly. Thanks in advance :)

enter image description here

Upvotes: 0

Views: 49

Answers (2)

JB Nizet
JB Nizet

Reputation: 691715

<div ng-repeat="section in sections">
  {{ section.name }}
  <div ng-repeat="subsection in section.subsections">
     {{ subsection.name }}
  </div>
  <button ng-click="addSubsectionTo(section)">Add subsection</button>
</div>
<button ng-click="addSection()">Add section</button>

Upvotes: 0

Sajal
Sajal

Reputation: 4401

There are probably many ways to do this, one of them could be to initialize an array for Parent Sections and other for child sections. The child would keep knowledge about who its parent is.

See the working plunker here: Demo

Two arrays:

$scope.section = [{id: 1}, {id:2}];

$scope.subSection = [{id:1, parentId: 1}, {id:2, parentId: 1},{id:3, parentId: 2}];

View:

<div ng-repeat="parent in section">
   <span>Section {{parent.id}}</span>
     <pre>
     <div ng-repeat="child in subSection" ng-if="child.parentId == parent.id">
        <span>SubSection {{child.id}}</span>
     </div>
      <button ng-click="addSubSection($index + 1)">Add SubSection</button>
     </pre>
</div>
<button ng-click="addSection()">Add Section</button>

Upvotes: 1

Related Questions