2016-01-22 58 views
0

我有一個帶有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>

回答

1

要刪除兄弟指示,重新編譯該元件,而不同級的指示和更換元件。

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