gpt4 book ai didi

javascript - $broadcast 和 $on 不适用于基于 ng-if 的模板

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:25 24 4
gpt4 key购买 nike

我在从父作用域向子作用域广播事件时遇到问题,我认为根核心可能是未初始化的子 Controller 。

假设我有 html:

<div ng-controller="ParentController">
<button type="button" ng-click="show()">Show Template</button>

<div ng-if="showTemplate">
<div ng-include="'template.html'" ng-controller="ChildController"></div>
</div>

</div>

和 Controller :

var myApp = angular.module("myApp", []);

myApp.controller('ParentController', ['$scope', function ($scope) {
$scope.show = function(){
$scope.showTemplate = true;
$scope.$broadcast("showEvent", 1);
};

}]);

myApp.controller('ChildController', ['$scope', function ($scope) {
$scope.$on("showEvent", function(event, id){
alert(id);
});
}]);

当点击按钮 Show Template 时,标志 showTemplate 被设置为显示模板,同时一个事件 showEvent 被广播到子范围。

但是 ChildController 中的作用域无法捕获此事件,因为子 Controller 可能会稍后初始化。

有什么办法可以解决这个问题吗?

这里的代码:http://plnkr.co/edit/HV6aco

最佳答案

将广播调用包装到 $timeout 中,我相信你可以开始了

$timeout(function() { $scope.$broadcast("showEvent"); },0);

关于javascript - $broadcast 和 $on 不适用于基于 ng-if 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357108/

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