2
我使用引導彈出模態窗口,並試圖$發射和事件,但由於某種原因,主頁面沒有檢測到事件。這是一個非常簡單的設置,但我不明白爲什麼。從我看到Batarang時可以看出,彈出窗口是主應用程序範圍的子範圍,所以我認爲它會起作用,但它不起作用。在這個簡單的應用程序中,當您在彈出窗口中按下「確定」時,它應該在父範圍中設置一個值。這裏有一個plunker:
http://plnkr.co/edit/F2W1LaWSsqinaFpiISAr?p=preview
//Here's code where $emit is called in the child (Factory):
var modalInstance = $modal.open({
templateUrl: 'popupMyWindow.html',
pScope: parentScope,
controller:
function($scope, $modalInstance){
$scope.ok = function() {
$scope.$emit('ModalSelect', 'hello world');
$modalInstance.close(null);
}
},
//Here's where $on is called in the main controller:
$scope.$on('ModalSelect', function (event, selected) {
console.log('ModalSelect called successfully');
$scope.selectedValue = selected;
});
謝謝!
謝謝,使用廣播從rootscope的伎倆 – Rob 2014-12-03 04:57:58
然而,這是不好的做法。首先,性能:root會將$發送給應用程序中的所有子範圍,無論它們是否正在偵聽。其次,你創建一個依賴到rootScope,從而降低可重用性(請參閱:http://stackoverflow.com/questions/24830679/why-we-use-rootscope-broadcast-in-angularjs) – SKuijers 2015-03-18 10:08:13
準確地說,'$ emit'氣泡建立分級鏈,'$ broadcast' - 向下。所以,root會將'$ emit'只發送給'$ rootScope。$ on'監聽器。但即使使用'$ broadcast' - 性能問題已得到解決 - [請參閱此答案](http://stackoverflow.com/a/19498009/968155) - 只有實際的聽衆纔會收到通知。 – 2015-03-18 14:07:50