AngularJS从DOM中删除自定义指令和子指令 [英] Angularjs remove custom directive and child directives from DOM
问题描述
我有一个页面angularjs应用程序.我使用$ routeProvider加载以下代码中所示的自定义指令.
I have a single page angularjs app. I use $routeProvider to load up custom directives shown in the code below.
现在,每个加载的自定义指令都由其他子自定义指令组成.所有的自定义指令都有隔离的作用域.
Now each custom directive loaded is made up of additional sub custom directives. All the custom directives have isolated scopes.
我需要的是,当视图改变时,要破坏的范围以及从当前视图下的DOM中删除指令.我有以下代码.可以仅使用jQuery lite和/或angularjs来实现吗?如果是这样,如何从DOM中删除特定视图的父和子指令?提前致谢.
What I need is when the view changes is the scope to be destroyed as well as remove the directives from the DOM under the current view. I've got as far as the following code. Can this be achieved with Jquery lite and/or angularjs only? If so how do I remove the parent and child directives from the DOM for a particular view? Thanks in advance.
自定义指令表单
angular.module("form", [])
.directive("form",['$http','$rootScope','$location', function($http,$rootScope,$location){
return{
link: function(scope,element,attrs){
//functions go heere
//destroy scope and remove from DOM on route change
$rootScope.$on( "$routeChangeSuccess", function(event, next, current) {
if($location.path()!=='/form'){
scope.$destroy();
console.log('This should not be displayed on route change');
}
});
//function and scopes go here
},//return
restrict:"A",
replace:true,
templateUrl:"partials/form/form.html",//template
transclude:true, //incorporate additional data within
scope:{}
}//return
}])
ng-view/routeProvider
app.config(['$routeProvider',function($routeProvider) {
//configure the routes
$routeProvider
.when('/',{
// route for the home page
templateUrl:'partials/login/login.html',
controller:'loginCtrl'
})
.when('/home',{
// route for the home page
templateUrl:'partials/home/home.html',
template:'<div home></div>'
})
.when('/company',{
// route for the sites& companies
template:'<div company></div>'
})
.when('/form',{
// route for form
template:'<div form></div>'
})
.otherwise({
//when all else fails
templateUrl:'partials/login/login.html',
controller:'loginCtrl'
});
}]);
推荐答案
请参阅以下参考资料:
如何从DOM中手动获取Angular指令
Please see this reference:
How to manually take an Angular directive out of the DOM
根据参考资料:
步骤:
1.删除指令的作用域
2.删除指令的DOM
Steps:
1. Delete the directive's scope
2. Delete the directive's DOM
childScope.$destroy(); //IF THE DIRECTIVE WAS CREATED DYNAMICALLY OR ELSE WE MAY USE angular.element(DIRECTIVES-DOM).scope().$destroy()
$('.my-directive-placeholder').empty(); //DELETE DIRECTIVE'S DOM
这篇关于AngularJS从DOM中删除自定义指令和子指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!