2015-11-24 99 views
2

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

现在,每个加载的自定义指令都由附加的自定义指令组成。所有的自定义指令都有独立的作用域。

我需要的是当视图更改时是要销毁的作用域以及从当前视图下的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 

}])

纳克视点/ 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' 
     }); 

}]); 

回答

3

请参阅此参考:
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