Reputation: 417
Im trying to clone a div tag which contains few HTML elements with ng-click function,
But dynamically cloned and appended HTML elements not firing ng-click function,
Can anyone help me out
this is the code i used
angular.module('AddNewCab', [])
.controller('cabcontainer', ['$scope','$compile', function($scope,$compile) {
$scope.count = 0;
$scope.myFunc = function($compile) {
$scope.count=$scope.count+1;
var source = angular.element( document.querySelector( '#cabdata' ));
var container = angular.element( document.querySelector( '#cabcontainer' ));
var uniqueid='cabdata'+$scope.count;
var temp=$compile(source.clone().attr('id',uniqueid),$scope);
container.append(temp);
};
}]);
Upvotes: 2
Views: 8261
Reputation: 837
I don't how your HTML file is but I created one example of this.
Take a peek: https://plnkr.co/edit/ZQ7EYw5CB3DojCKs7Qlv
HTML:
<div ng-controller="cabcontainer">
<div id="cabdata">
<p>Test1</p>
<p>Test2</p>
</div>
<div id="cabcontainer">
<p>Clone here</p>
</div>
<input type="button" ng-click="myFunc()" value="Clone"/>
</div>
JS:
angular.module('AddNewCab', [])
.controller('cabcontainer', ['$scope','$compile', function($scope, $compile) {
$scope.count = 0;
$scope.myFunc = function() {
$scope.count=$scope.count+1;
var source = angular.element( document.querySelector( '#cabdata' ));
var container = angular.element( document.querySelector( '#cabcontainer' ));
var uniqueid='cabdata'+$scope.count;
var temp= $compile(source.clone().attr('id',uniqueid))($scope);
container.append(temp);
};
}]);
Note: I made some changes in your controller, for example, there is no need to put the $compile in you function because it's already injected on the controller by angular.
Upvotes: 7
Reputation: 292
If i do understand you right, you want to add an eventlistener to dynamically created elements? in that case i would use jQuery instead of ng-click. Someting like
$("parentElement").on("click", "elementToClick", function() {
//your code here
});
You could do the same with an angular directive, but jQuery was easier to explain. And if you need parameters, you can add them with data-attributes to the element and call them with
this.getAttribute("data-AttributeName")
Oh, and if you use ng-attributes, make them to data-ng-* (e.g. data-ng-click). Will bring no chances to functionality, but make your code html valid.
Upvotes: 0