3

我正在尝试使用以下方法将 AngularJS 中的事件发送到第二个控制器:

第一控制器:

    $scope.checkThemeContent = function(theme) {
    console.log("Trying to get cards for theme id: " +theme.id);
    console.log(theme);

    $scope.selectedTheme = theme;

    if(theme.count_of_cards >0) {
        //$scope.$emit('detailDisplayed', {});
        $scope.displayedTemplate = 'detail';
        $rootScope.$emit('detailDisplayed', {});
    } else {
        $scope.displayedTemplate = 'empty';
    }
};

第二个控制器:

 $rootScope.$on('detailDisplayed', function(event, args) {
        alert('Received');
        $scope.initDataGrid();
    });

但是没有触发事件。

我尝试反向使用范围,它可以工作。

请问哪里有问题?

我遵循了本教程:

http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

谢谢你的帮助。

4

2 回答 2

9

我尝试反向使用范围,它可以工作。

在我看来,您的代码的结构是在$on处理程序附加到之前发出事件的位置$rootScope。确保在发出事件之前已实例化第二个控制器。

于 2014-11-05T20:52:54.143 回答
3

记住:发射沿着原型链上升,广播下降。如果您已经在顶部(即$rootScope),它就不能再高了。用于$broadcast让事件全面触发。

$rootScope.$broadcast('detailDisplayed');

检查这篇文章:

https://blog.safaribooksonline.com/2014/04/08/refactoring-angularjs-get-hands-filthy/

于 2014-11-05T20:53:21.860 回答