删除指令属性不会删除侦听器
Removing directive attribute does not remove listener
我有一个带有 ng-click 属性的按钮。如果我删除 ng-click 属性,侦听器仍然存在。移除 ng-click 属性后如何移除事件监听器?
angular.module('testApp', ['ng'])
.directive('testDir', testDir)
.controller('testCtrl', testCtrl);
function testDir() {
return {
compile: (elem, attrs) => {
// Remove ng-click attribute
elem.removeAttr('ng-click');
}
};
}
function testCtrl($scope) {
$scope.count = 0;
$scope.handleClick = function() {
$scope.count++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
<div ng-controller="testCtrl">
<button test-dir ng-click="handleClick()">Click Me</button>
<p>
Count: {{count}}
</p>
</div>
</div>
要删除同级指令,re-compile 没有同级指令的元素并替换该元素。
angular.module('testApp').directive('testDir', function($compile) {
return {
link: (scope,elem, attrs) => {
// Remove ng-click attribute
attrs.$set('ngClick');
// Prevent infinite recursive re-compile
// Remove test-dir attribute
attrs.$set('testDir');
//Change button text
elem.text("New Click Me")
//re-compile
var newLinkFn = $compile(elem);
//replace
newLinkFn(scope, function transclude(clone) {
elem.replaceWith(clone);
});
}
};
});
我有一个带有 ng-click 属性的按钮。如果我删除 ng-click 属性,侦听器仍然存在。移除 ng-click 属性后如何移除事件监听器?
angular.module('testApp', ['ng'])
.directive('testDir', testDir)
.controller('testCtrl', testCtrl);
function testDir() {
return {
compile: (elem, attrs) => {
// Remove ng-click attribute
elem.removeAttr('ng-click');
}
};
}
function testCtrl($scope) {
$scope.count = 0;
$scope.handleClick = function() {
$scope.count++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
<div ng-controller="testCtrl">
<button test-dir ng-click="handleClick()">Click Me</button>
<p>
Count: {{count}}
</p>
</div>
</div>
要删除同级指令,re-compile 没有同级指令的元素并替换该元素。
angular.module('testApp').directive('testDir', function($compile) {
return {
link: (scope,elem, attrs) => {
// Remove ng-click attribute
attrs.$set('ngClick');
// Prevent infinite recursive re-compile
// Remove test-dir attribute
attrs.$set('testDir');
//Change button text
elem.text("New Click Me")
//re-compile
var newLinkFn = $compile(elem);
//replace
newLinkFn(scope, function transclude(clone) {
elem.replaceWith(clone);
});
}
};
});