2014-04-04 167 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個控制器上運行?