Nathan  Meunier Nathan Meunier - 4 months ago 51
AngularJS Question

Dynamically add a directive with a ng-click inside

EDIT: plunker : https://embed.plnkr.co/fHPQfbUQ1lvZBJsDNQR5/

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

"http://errors.angularjs.org/1.5.6/$parse/syntax?p0=%7B&p1=invalid%20key&p2=17&p3=updateTypeZone(%7B%7Bcount%7D%7D)&p4=%7Bcount%7D%7D"
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(){

angular.element(document.getElementById('box')).append($compile("<new></new>")($scope));
$scope.count++;
}

$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(){
return{
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>'+
'</button>'

};
});

connectItApp.directive('new', function($compile){
return{
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>


etc..

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

Answer

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++) {
      input.push(i);
    }
    return input;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "app" ng-controller="myController">
  <button ng-click="add()">add</button>
  <ul>
    <li ng-repeat="n in range()">listing {{ n }}</li>
  </ul>
</div>

Comments