2015-11-24 132 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