Angularjs从DOM中删除自定义指令和子指令

时间:2015-11-24 09:08:20

标签: angularjs dom

我有一个单页angularjs应用程序。我使用$ routeProvider加载下面代码中显示的自定义指令。

现在加载的每个自定义指令都由其他子自定义指令组成。所有自定义指令都有隔离的范围。

我需要的是视图更改是要销毁的范围,以及从当前视图下的DOM中删除指令。我已经达到了以下代码。这可以通过Jquery lite和/或angularjs来实现吗?如果是这样,我如何从DOM中删除特定视图的父指令和子指令?提前致谢。

自定义指令表

 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-视图/ 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'
        });

}]);

1 个答案:

答案 0 :(得分:4)

请参阅此参考文献:
 How to manually take an Angular directive out of the DOM

根据来源参考:

步骤:
1.删​​除指令的范围
2.删除指令的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