floatyourboat
floatyourboat

Reputation: 83

AngularJS - Add DOM elements on counter++

I'm quite new to AngularJS and have read a little bit about how directives work. I'm still not quite sure about how to go about this problem though.

Here's the setup:

I have buttons on a view like so:

<div class="parent">
  <button class="firstButton" type="button" ng-click="fetchData(param1, param2)"></button>
  <button class="secondButton" type="button" ng-click="fetchData(param1, param2)"></button>
  <button class="thirdButton" type="button" ng-click="fetchData(param1, param2)"></button>
  <button class="fourthButton" type="button" ng-click="fetchData(param1, param2)"></button>
</div>
<div class="dataPanel">

 <!-- This is where DIVs will be placed -->

</div>

Then in my controller I have:

// Init value of counter here
var counter = 0;

$scope.fetchData = function (param1, param2) {

  // Do something with parameters here

  counter++;
}

Ideal scenario would be when user clicks on firstButton, fetchData() initiates, getting data from a factory, then increments value of counter. A div would be created from counter value change. The number of divs created in the DOM would depend on counter value. Each created div is also populated with data gotten from each respective fetchData(). This goes on as user clicks on more buttons, although in my current project, I've limited the number of allowed dataSet duplicates.

End result of the HTML would then be:

<div class="dataPanel">
 <div class="dataSet">  <!-- from firstButton -->
  <p>{{dataFromFirstButton}}</p>
 </div>
 <div class="dataSet">  <!-- from secondButton -->
  <p>{{dataFromSecondButton}}</p>
 </div>
 <div class="dataSet">  <!-- from thirdButton-->
  <p>{{dataFromThirdButton}}</p>
 </div>
</div>

What's the Angular way of doing this? I've read directives can pretty much do everything when it comes to DOM manipulation but have no idea on where to start when it comes to actually constructing the directive.

Upvotes: 0

Views: 114

Answers (1)

Fridjon Gudjohnsen
Fridjon Gudjohnsen

Reputation: 827

One way to accomplish this is to use ng-repeat directive to draw the divs based on an array, that is initially empty. You can set the html up so that a div is drawn for each object in the array, since the array is empty no div is initially drawn.

<div class="dataSet" ng-repeat="n in arrays[0]">
  This div from button 1 contains: {{n.data}}
</div>

When you click on the buttons you can add an object, containing any needed data, to the array. Then a div will be drawn for the appropriate ng-repeat directive.

  $scope.arrays = [ [], [], [], []];

  $scope.fetchData = function (data, idx) {
    $scope.arrays[idx].push({data: data});
  }

See plunker here.

Upvotes: 1

Related Questions