javascript - AngularJS - $scope.$new() 创建的作用域何时被删除。垃圾收集器或 Angular 会处理它吗?

标签 javascript angularjs memory-leaks garbage-collection angularjs-scope

我想知道如何在下面的场景中删除 $scope.$new() 创建的作用域。

我的场景 - 由 $scope.$new() 创建一个新范围,添加一些属性并将其传递给 Angular 脚本模板

<script type="text/ng-template" id="row-details.html">
<tr><td>code</td></tr>
</script>

它会动态创建一个新的表行。所以每<tr>在我的例子中,row 得到了一个新的范围。每当在我的 html 表格中双击行或列时,我就会动态创建表格行。

现在在某些事件中,例如 - 在某些父行或列或任何地方“双击”,我删除了通过 $scope.$new() 使用新范围的模板创建的这个新行,我的问题是这是否也会删除对 $scope.$new() 范围的引用,或者我必须手动删除它,或者在某个时候垃圾收集器会删除它,因为自从使用的表行以来没有对它的引用它已从 DOM 中删除。

对上述问题的总体关注是我想确保应用程序中没有内存泄漏。

所以总的来说我有两个问题 -

  1. 从 DOM 中删除相关 DOM 行后, Angular 收集器或垃圾收集器是否会自动删除新作用域。
  2. 如何通过 Chrome 开发工具或任何其他方式对此进行测试,无论引用是否被删除,并且该特定代码是否存在内存泄漏。

如果您需要更多详细信息,请告诉我。 谢谢!

最佳答案

当有人调用其 $destroy 方法时,作用域将被删除。

当其祖先之一被删除时,范围也会被删除。

“删除”意味着作用域及其子作用域将不再接收摘要调用,并且应该进行垃圾收集。

来自documentation $new$destroy 方法的范围。

$new(isolate, parent);

Creates a new child scope.

The parent scope will propagate the $digest() event. The scope can be removed from the scope hierarchy using $destroy().

$destroy() must be called on a scope when it is desired for the scope and its child scopes to be permanently detached from the parent and thus stop participating in model change detection and listener notification by invoking.

$destroy();

Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection.

具体来说,对于您的问题,您必须对您创建的子作用域调用 $destroy 。仅删除 DOM 元素不会触发它 - 子作用域仍然位于作用域层次结构中并且具有对其的引用。

plunker - 用于说明

关于javascript - AngularJS - $scope.$new() 创建的作用域何时被删除。垃圾收集器或 Angular 会处理它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792040/

相关文章:

javascript - 在 yandex map 中获取多边形内单击点的地址

javascript - 如何将 JSON 对象传递给 EJS 中的内联 javascript

angularjs - 在 Angular js日期选择器指令中仅隐藏清除按钮

javascript - angularJS:单元测试给出:未知提供者:$httpProviderProvider <- $httpProvider

java - 安卓/Java : Fragment instantiating causes memory leak?

xcode - “Allocated Prior to Attach” 在 Xcode 仪器中是什么意思?

JavaScript 定时器事件

javascript - 带有 css 和 JS 的 Fiverr 样式文本区域

c - 最小的 bison/flex 生成的代码有内存泄漏

javascript - React 和文本输入 - 使用 onBlur 还是 onChange?