【发布时间】:2016-02-17 06:25:43
【问题描述】:
我正在尝试动态添加字段,并在指令的 link 函数中绑定 click 事件。但随着我添加更多字段,它似乎被触发了几次。请参阅下面的示例 -
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>
我想让click 事件只针对特定元素触发一次。
【问题讨论】:
标签: javascript jquery angularjs angularjs-directive angularjs-scope