What I need is the functionality of two ng-views. Because I can\'t I want to change the innerHTML of something and compile it. The problem I have is when I change the content ag
Thanks for you good solution. I've just posted some implement code
.directive('modal', function($templateCache, $compile) {
return function(scope, element, attrs) {
var currentModalId = attrs.modalId;
var templateHtml = $templateCache.get(attrs.template);
var modalScope, modalElement;
scope.$on('modal:open', function(event, modalId) {
if(modalId == null || currentModalId === modalId) {
openModal();
}
});
scope.$on('modal:close', function(event, modalId) {
if(modalId == null || currentModalId === modalId) {
closeModal();
}
});
function openModal() {
// always use raw template to prevent ng-repeat directive change previous layout
modalElement = $(templateHtml);
// create new inherited scope every time open modal
modalScope = scope.$new(false);
// link template to new inherited scope of modal
$compile(modalElement)(modalScope);
modalElement.on('hidden.bs.modal', function() {
if(modalScope != null) {
// destroy scope of modal every time close modal
modalScope.$destroy();
}
modalElement.remove();
});
modalElement.modal({
show: true,
backdrop: 'static'
});
}
function closeModal() {
if(modalElement != null) {
modalElement.modal('hide');
}
}
};
});
The solution for this problem is creating a new child scope. All bindings with parent scope work because of scope Inheritance. When I need to change the content, I simply destroy the child scope, avoiding memory leaks.
I've also made and getter and setter methods for the child scope to avoid poluting que parent scope, in case the other content uses disposable variables
To manually remove the element do an element.remove()
. Sounds like you also want to destroy the scope of your compiled element so you can do that too by doing scope.$destroy();
or $scope.$destroy();
depending on if you're in a directive or not.
http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy