1

I've already seen this post with the same subject: Dynamically add directive in AngularJS

but I'm not enough familiar with angular to use this solution in my case.

In my case I'm trying to dynamically add a directive (based on an outer html) to a div after button-clicked:

        <div class="charges" id="charges">
            <my-headcharges></my-headCharges>
            <my-charges></my-charges>

        </div>

Nou can see my div with two directives which I created and placed under the div hard-coded. Now I want to add the same directives, but many times and after a button-clicked.

thanks :)

Community
  • 1
  • 1
Tom Baum
  • 23
  • 5

1 Answers1

1

You can use ng-repeat

var myApp = angular.module("myApp", []);
myApp.controller("myController", ["$scope",
  function($scope) {
    $scope.items = []
    $scope.addTimes = function() {
      $scope.items.push({
        name : new Array(7).join().split(',').map(function(it){return String.fromCharCode(Math.floor(Math.random() * (122 - 97 + 1)) + 97)}).join("")
        });
    };
  }
]);
<html ng-app="myApp">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body ng-controller="myController">
    <button ng-click="addTimes()">Add</button>
    <div class="charges" ng-repeat="item in items">
      <my-headcharges>Hello {{item.name}}</my-headCharges>
      <my-charges></my-charges>
    </div>
</body>

</html>