我正在尝试在页面加载时向另一个 Controller 广播事件。尽管接收广播的 Controller 尚未初始化,因此未对该事件使用react。
app.controller('ControllerOne', ['$scope', '$rootScope') {
if(someVar) {
$rootScope.$broadcast("my-event");
}
}]);
app.controller('ControllerTwo', ['$scope', '$rootScope') {
$scope.$on("my-event", function() {
console.log("Event hit!");
})
}]);
我的 ControllerOne
是我的路线的 Controller ,我的 ControllerTwo
是通过 ng-include
加载的 View 的 Controller 该页面。
因此,首先调用 ControllerOne
,随后在初始化 ng-include
时调用 ControllerTwo
。
如何在不使用诸如 $timeout
之类的黑客方法的情况下从 ControllerOne
初始化到 ControllerTwo
的事件?有没有比使用 $broadcast
更好的方法来解决这个问题?
最佳答案
Is there a better way to approach this instead of using $broadcast?
我认为答案可能是"is",但如果不知道您到底在广播什么以及为什么,就很难知道。
例如,目前, Controller 一运行就广播事件。您是否有理由不能只执行以下操作(独立于 ControllerOne
):
app.controller('ControllerTwo', ['$scope', '$rootScope') {
if(someVar) {
console.log("Event hit!");
}
}]);
我怀疑您可能会建议 someVar
只能在 ControllerOne
中访问,此时我建议您通过服务来访问它并使用该方法。
如果您提供更多关于您想要实现的目标的背景信息,我会将答案更新得更加具体。
关于javascript - Angular 广播初始化太早,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31807890/