我试图理解 Controller 的 $onDestroy 方法和 $scope.$destroy() 之间的区别。
定义表示当需要销毁组件的包含范围时调用 $onDestroy。但这与 $scope.$destroy() 的情况不一样吗?
根据我在 https://plnkr.co/edit/9RlS8OLxAoyK80WPMJaN?p=preview 创建的 plunker ,
<div ng-controller="ParentController">
<button ng-click="func()">Parent</button>
<br><br>
<div ng-controller="ChildController">
<button ng-click="childFunc()"> Child </button>
<br><br>
<comp> </comp>
</div>
</div>
我注意到两种情况。
当我从父 Controller 或子 Controller 调用 $destroy() 时,组件中会触发 $onDestroy 和 $scope.$on('$destroy') 事件。这是有道理的,因为当父作用域被破坏时,组件的包含作用域也被破坏。但是,我仍然可以单击“Component FUNC”按钮并调用与其关联的函数。为什么会出现这种情况?
当我从组件本身调用 $destroy() 时,仅触发 $scope.$on('destroy') 事件,而 $onDestroy 未触发。另外,我无法像案例#1 中那样访问“Component FUNC”按钮。
有人可以解释一下这两种情况的区别吗?
这不是现实生活中的用例,而是我想理解的东西。
谢谢。
最佳答案
查看以下链接:
https://github.com/angular/angular.js/issues/15073
https://github.com/angular/angular.js/issues/14376
总而言之,他们给出的解释如下:
There is a misconception that controller.$onDestroy() is equivalent to $scope.$on('$destroy'), where $scope is the scope passed to the controller. This is not always the case.
More specifically, controller.$onDestroy() is called when the scope where the controller "lives in" gets destroyed. When you have an isolate scope directive, the scope passed (as $scope) to the controller is not the scope that the controller lives in, it is a child-scope that is created for the directive's template. Thus, calling $scope.$destroy() will NOT destroy the scope that the controller lives in (and NOT call controller.$onDestroy()).
The only case, where controller.$onDestroy() is equivalent to $scope.$on('$destroy') is when having a directive with scope: false. This means that no new scope is created, so the scope passed (as $scope) to the controller is the same scope that the controller lives in.
这解释了第二种情况,但我仍然不明白为什么即使在调用了 $destroy() 之后也可以调用与“Component FUNC”按钮关联的函数。
我希望这会有所帮助。
关于javascript - Angular 1.5 组件 $onDestroy 和 $scope.$destroy() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41788721/