don*_*las 21 javascript dom angularjs
我需要的是两个ng-views的功能.因为我不能想要改变某些东西的innerHTML并编译它.我遇到的问题是当我再次更改内容时,我可以编译,但有角度删除它自己的绑定,或者我必须手动执行,如果是这样,怎么样?
编辑:解释
我想创建一个模态,我可以更改其内容并绑定到不同的范围(因此$ compile).但是我不想破坏整个模态,只是破坏它的一些内容,而是变成另一个.我的主要疑问是,如果通过删除一些已编译的HTML,它可能会导致内存泄漏.
解决了
对于这个问题,我创建了一个新的子范围(使用$ new)并在我更改内容时将其销毁.谢谢你的一切
Mat*_*erg 20
要手动删除元素,请执行element.remove().听起来你也想破坏已编译元素的范围,所以你也可以通过做scope.$destroy();或$scope.$destroy();依赖于你是否在指令中来做.
http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy
谢谢你的好解决方案.我刚刚发布了一些实现代码
.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');
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
这个问题的解决方案是创建一个新的子作用域。由于作用域继承,所有与父作用域的绑定都有效。当我需要更改内容时,我只需销毁子作用域即可,避免内存泄漏。
我还为子作用域创建了 getter 和 setter 方法,以避免污染父作用域,以防其他内容使用一次性变量
| 归档时间: |
|
| 查看次数: |
42367 次 |
| 最近记录: |