2014-04-04 118 views
1

我有一个按钮,其触发的自定义模态(I所使用的模态从这里http://codepen.io/m-e-conroy/pen/ALsdF共享服务中AngularJS

按钮驻留在MainController控制器。

MainController

app.controller('MainController', function($scope, sharedService) { 
    $dialogs.create('dialog.html', 'SecondController', 
     {}, {key: false, back: 'static'}); 

    // Start broadcast 
    sharedService.prepForBroadcast('Hello AngularJS'); 
}); 
SecondController
app.controller('SecondController', function($scope, sharedService) { 
    // This piece of code doesn't get called. 
    $scope.$on('handleBroadcast', function() { 
     console.log('received broadcast'); 
    }); 
}); 

sharedService

app.factory('sharedService', function($rootScope) { 
    var data = {message: ''}; 

    data.prepForBroadcast = function(message) { 
     this.message = message; 
     $rootScope.$broadcast('handleBroadcast'); 
    }; 

    return data; 
}); 

我的问题是

:在SecondController,为什么它不收听广播?为什么那段代码(在上面的SecondController中评论过)永远不会被执行?

回答

1

在第二控制器使用$ rootScope.on没有$ scope.on

服务正在改变rootcope而不是第二个控制器范围。

+0

谢谢。但它仍然不起作用.. – sc1013

0

我只是做了一个简单的设置你的例子,一切似乎工作,所以必须是你的代码中的其他东西。工作

例如使用代码: http://jsbin.com/rosutoya/2/edit

难道你没有看到你所期望的,因为你的网页实际上并不有2个控制器上运行?