Tim*_*Mac 24 angularjs angularjs-directive angularjs-scope
我无法弄清楚为什么在以下示例中未触发$ destroy事件.有人可以解释为什么它没有被触发,在什么情况下它会被触发?
以下是plunkr:http://plnkr.co/edit/3Fz50aNeuculWKJ22iAX?p=preview
angular.module('testMod', [])
.controller('testCtrl', function($scope){
$scope.removeElem = function(id) {
var elem = document.getElementById(id);
angular.element(elem).remove();
}
}).directive('testDir',[function() {
return {
scope:true,
link: function(scope) {
console.log('in directive');
scope.$on('$destroy', function(){
alert('destroyed');
})
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
<body ng-controller='testCtrl'>
<div testDir id='test'>I will be removed.</div>
<button ng-click='removeElem('test')'>remove</button>
</body>
Run Code Online (Sandbox Code Playgroud)
fby*_*ite 24
问题是你正在监听$destroy事件scope,但是$destroy正在触发事件element.
来自angular.js源码(我确定它已经在网站上的某个地方记录过,但我没看过):
$destroy- AngularJS拦截所有jqLite/jQuery的DOM破坏apis,并在被删除的所有DOM节点上触发此事件.这可用于在删除DOM元素之前清除任何第三方绑定.
你的指令应为(注意,我说scope,element和attrs作为link参数):另外,这里是一个plunker.
directive('testDir',[function() {
return {
scope:true,
link: function(scope,element,attrs) {
console.log('in directive');
element.on('$destroy', function(){
alert('destroyed');
})
}
};
}]);
Run Code Online (Sandbox Code Playgroud)