I'm trying to add fields dynamically and I'm binding click
event in the directive's link
function. But it seems to be firing several times as I add more fields. See the example below -
var clicks = 0;
var app = angular.module('test', []);
app.directive('control', function($compile) {
var linker = function(scope, element, attrs) {
element.html('<button style="background:grey;">Button ' + scope.count + '</button>');
element.bind('click', function() {
clicks++;
$('#clicks').html('Clicked ' + clicks + ' times')
});
$compile(element.contents())(scope);
};
return {
restrict: 'E',
scope: {
count: '@'
},
link: linker
}
});
app.controller('TestController', function($scope, $compile) {
$scope.count = 1;
$scope.addControl = function() {
$('#content').append('<control count="' + $scope.count+++'"></control>');
$compile($('#content').contents())($scope);
};
});
#content {
margin-top: 10px;
}
#clicks {
margin-top: 10px;
}
p {
color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="TestController">
<button ng-click="addControl()">Add Button</button>
<div id="content"></div>
<div id="clicks"></div>
</div>
<p>Add multiple buttons and click the button that was added in the beginning. Notice the Clicks to be increased multiple times.</p>
<p>For instance, add a bunch of buttons and click Button 1</p>
I'd like to have the click
event fired only once for a specific element.