$ rootScope。$ emit不工作

时间:2014-11-05 20:49:21

标签: javascript angularjs emit

我尝试使用以下方法将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/

感谢您的帮助。

2 个答案:

答案 0 :(得分:9)

  

我试图反向使用范围并且它可以工作。

听起来像我的代码是在$on处理程序附加到$rootScope之前将事件发送到的位置。确保在发出事件之前已实例化第二个控制器。

答案 1 :(得分:3)

请记住:发射上升到原型链,广播下降。如果你已经位于最前面(即$rootScope),它就不会更高。使用$broadcast让事件全面触发。

$rootScope.$broadcast('detailDisplayed');

查看这篇文章:

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

相关问题