有人可以帮助我理解我们应该使用$rootScope.$on和的方式$scope.$on.
我知道它主要用于听取不同的范围($ rootScope和$ scope).
我的查询适用于以下场景:
我可以使用:$ rootScope.$ $ with $ rootScope.$ on
要么
我应该更喜欢:$ rootScope.$ with $ scope.$ on 我知道这不是一个好选项,因为它会向所有
$scopeobj 广播.
要么
我要去:$ rootScope.$ with $ rootScope.$ on
如您所见,我需要处理$ rootScope级别的事件.
以上3个实现有什么区别?
lin*_*lin 21
这是一个很好的问题,有一个解释.
$scope.on('event');会听听$scope.$broadcast('event')&$rootScope.$broadcast('event')
$rootScope.on('event');会听听$rootScope.$broadcast('event')&$rootScope.$emit('event')
$scope.on(); 当控制器在视图或组件中丢失它时,将被自动销毁(被破坏). $rootScope.$on()手动销毁.$rootScope.on()://bind event
var registerScope = $rootScope.$on('someEvent', function(event) {
console.log("fired");
});
// auto clean up `$rootScope` listener when controller getting destroy
// listeners will be destroyed by calling the returned function like registerScope();
$scope.$on('$destroy', registerScope);
Run Code Online (Sandbox Code Playgroud)
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $rootScope) {
var registerScope = null;
this.$onInit = function () {
//register rootScope event
registerScope = $rootScope.$on('someEvent', function(event) {
console.log("fired");
});
}
this.$onDestroy = function () {
//unregister rootScope event by calling the return function
registerScope();
}
});
Run Code Online (Sandbox Code Playgroud)
$scope.on()和 的不同行为$rootScope.on().通过切换此plunkr中的视图,控制器将被重新绑定到您的视图.该$rootScope.on();事件被绑定每次切换视图时不破坏前视图的事件绑定.以这种方式,$rootScope.on()听众将被堆叠/倍增.这不会发生在$scope.on()绑定中,因为它将通过切换视图来销毁(在DOM中丢失E2E绑定表示 - >控制器被破坏).
$emit&之间的区别$broadcast是:$rootScope.$emit()事件只触发$rootScope.$on()事件.$rootScope.$broadcast()将触发$rootScope.$on()和 $scope.on()事件(几乎听到这个事件).$scope.$emit()将触发所有$scope.$on父项(父控制器中的范围)和$rootScope.$on().$scope.$broadcast将仅触发$scope及其子节点(子控制器中的范围).| 归档时间: |
|
| 查看次数: |
14117 次 |
| 最近记录: |