我无法弄清楚为什么在以下示例中未触发$ 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) 在下面的例子中,我不明白为什么在删除元素后,angular仍然会解析解析器和格式化程序.我应该在指令中手动清理ngModel控制器吗?如果是这样,我该怎么做?
要查看我在说什么,请查看plunker,和
plunker:http://plnkr.co/edit/R7v5nB8JaQ91WcDGU8BC?p = preview
angular.module('testMod', [])
.controller('testCtrl', function($scope){
$scope.test = "test";
$scope.removeElem = function(id) {
var elem = document.getElementById(id);
angular.element(elem).remove();
}
}).directive('testDir',[function() {
return {
require: 'ngModel',
scope:true,
link: function(scope, elem, attr, ctrl) {
console.log('in directive');
ctrl.$parsers.unshift(function (newValue) {
console.log('directive parser');
return newValue;
});
ctrl.$formatters.unshift(function (newValue) {
console.log('directive formatter');
return newValue;
});
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
<body ng-controller='testCtrl'>
<input id='test' test-dir ng-model='test'/>
<button ng-click="removeElem('test')">remove</button>
<button ng-click="test = test + 'a'">change model</button>
<div>{{test}}</div> …Run Code Online (Sandbox Code Playgroud)