删除指令属性不会删除侦听器

删除指令属性不会删除侦听器

本文介绍了删除指令属性不会删除侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有ng-click属性的按钮。如果我删除ng-click属性,则侦听器仍然存在。当我删除ng-click属性时如何删除事件监听器?

I have a button with a ng-click attribute. If I remove the ng-click attribute, the listener persists. How can I remove the event listener when I remove the ng-click attribute?

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>

推荐答案

要删除兄弟指令,请在没有兄弟指令的情况下重新编译元素并替换元素。

To remove sibling directives, re-compile the element without the sibling directives and replace the element.

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);
      });
    }
  };
});

这篇关于删除指令属性不会删除侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:43