如何在 AngularJS 1.2 中从控制器中正确删除指令范围
How to properly delete the directive scope from controller in AngularJS 1.2
我正在尝试通过控制器调用从页面中删除一个指令实例,但遇到了某种我似乎无法弄清楚的摘要问题。看起来范围没有得到正确清理,元素被删除后仍然触发事件。感谢帮助。
这是我修剪过的 HTML:
<div ng-controller="MyCtrl">
<div class="directive-text" ng-style="style('green')" my-directive>This is my directive</div>
<a ng-click="delete()">[ delete ]</a>
</div>
还有我的 JS:
var demo = angular.module('demo', []);
demo.directive('myDirective', function() {
return {
link: function($scope, $element) {
console.log('init directive');
}
}
});
demo.controller("MyCtrl", ['$scope', '$compile', function($scope, $compile) {
$scope.items = {
'red': {
style: {
color: 'red'
}
},
'green': {
style: {
color: 'green'
}
}
};
$scope.style = function(color) {
return $scope.items[color].style;
}
$scope.delete = function() {
console.log('deleting...');
$('.directive-text').remove();
delete $scope.items['green'];
};
}]);
在 SO 上搜索 "angular remove directive from DOM" 得到了这个:
Angularjs remove custom directive and child directives from DOM
简短版本:在将指令从 DOM.
中删除之前,您应该销毁该指令的范围
$scope.delete = function() {
console.log('deleting...');
// Destroy the directive's scope
angular.element(document.querySelector(".directive-text")).scope().$destroy();
// I changed the following line to avoid using jQuery
angular.element(document.querySelector(".directive-text")).remove();
delete $scope.items['green'];
};
我正在尝试通过控制器调用从页面中删除一个指令实例,但遇到了某种我似乎无法弄清楚的摘要问题。看起来范围没有得到正确清理,元素被删除后仍然触发事件。感谢帮助。
这是我修剪过的 HTML:
<div ng-controller="MyCtrl">
<div class="directive-text" ng-style="style('green')" my-directive>This is my directive</div>
<a ng-click="delete()">[ delete ]</a>
</div>
还有我的 JS:
var demo = angular.module('demo', []);
demo.directive('myDirective', function() {
return {
link: function($scope, $element) {
console.log('init directive');
}
}
});
demo.controller("MyCtrl", ['$scope', '$compile', function($scope, $compile) {
$scope.items = {
'red': {
style: {
color: 'red'
}
},
'green': {
style: {
color: 'green'
}
}
};
$scope.style = function(color) {
return $scope.items[color].style;
}
$scope.delete = function() {
console.log('deleting...');
$('.directive-text').remove();
delete $scope.items['green'];
};
}]);
在 SO 上搜索 "angular remove directive from DOM" 得到了这个: Angularjs remove custom directive and child directives from DOM
简短版本:在将指令从 DOM.
中删除之前,您应该销毁该指令的范围$scope.delete = function() {
console.log('deleting...');
// Destroy the directive's scope
angular.element(document.querySelector(".directive-text")).scope().$destroy();
// I changed the following line to avoid using jQuery
angular.element(document.querySelector(".directive-text")).remove();
delete $scope.items['green'];
};