gpt4 book ai didi

events - AngularJS 广播不适用于第一个 Controller 负载

转载 作者:行者123 更新时间:2023-12-03 18:26:27 25 4
gpt4 key购买 nike

在这个 PlunkerDemo 中,我试图将一个事件从父 Controller 广播到子 Controller 。然而,直接在父 Controller 中这样做是行不通的。处理程序不注册事件。但是,基于 ng-click 或基于 setTimeout 执行此操作,它可以工作。是因为范围生命周期吗?

http://beta.plnkr.co/edit/ZU0XNK?p=preview

请参阅已接受答案的评论。他们解释了我的问题。

最佳答案

对 angular 范围的任何更改都必须在 angular 框架内进行,如果必须在框架外进行任何更改,我们必须使用 .$apply功能。

$apply() is used to execute an expression in angular from outside of the angular framework.



在您的情况下,您正在触发 $broadcastsetTimeout ,在 angular 框架之外调用回调。

所以你有两个解决方案,要么使用 $timeout由angular提供的服务或使用 .$apply功能。

我更喜欢使用 $timeout功能。
var ParentCtrl = function($scope, $rootScope, $timeout){

$scope.broadcast = function(){
$rootScope.$broadcast('Sup', 'Here is a parameter');
};

$timeout(function(){
$scope.$broadcast('Sup');
}, 1000);

//this one does not work! Most likely due to scope life cycle
$scope.$broadcast('Sup');

$scope.$on('SupAgain', function(){
console.log('SupAgain got handled!');
});

};

演示: Fiddle

使用 $apply
setTimeout(function(){
$scope.$apply(function(){
$scope.$broadcast('Sup');
});
}, 1000);

关于events - AngularJS 广播不适用于第一个 Controller 负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15676072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com