Nathan  Meunier Nathan Meunier - 1 year ago 120
AngularJS Question

Dynamically add a directive with a ng-click inside

EDIT: plunker :

I got a problem when I append my directive in my html, I have an error:

when I click on the button.

my code: ( here my controller )

connectItApp.controller('Inputcontroller',['$scope','$http', '$compile' , function($scope, $http, $compile) {
$scope.count = 1;

$scope.addInput = function(){


$scope.updateTypeZone = function (concernedId) {
/*some stuff */

(here my two directives they are called in a div witch as Inputcontroller as controller)

connectItApp.directive('champText', function(){
restrict: 'E',
template: '<button type="button" class="btn btn-default btn-lg btn-block" ng-click="addInput()" >'+
'<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span><span style="margin-left:10px;">Text</span>'+


connectItApp.directive('new', function($compile){
restrict: 'E',
templateUrl: 'views/new-input.html'


(and here views/new-input.html)

<div ng-click='updateTypeZone({{count}})'>toto</div>

My goal is when I click on the button, I want that a new div append in the like this exemple:

If I click one time , I will have

<div id="box"><div ng-click='updateTypeZone(1)'></div></div>

If I click a second time, I will have

<div id="box"><div ng-click='updateTypeZone(1)'></div><div ng-click='updateTypeZone(2)'></div></div>


I don't know how I can solve my problem.

Answer Source

Remember your view is just a represenation of your controller. Instead of adding the html to the dom manually you would simply add it to your template with ng-repeat and adjust the controller.

var app = angular.module("app", []);

app.controller('myController', function($scope) {
  $scope.count = 0;
  $scope.add = function() {
    $scope.count += 1;
  $scope.range = function() {
    var input = [];
    for (var i = 0; i <= $scope.count; i++) {
    return input;
<script src=""></script>
<div ng-app = "app" ng-controller="myController">
  <button ng-click="add()">add</button>
    <li ng-repeat="n in range()">listing {{ n }}</li>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download