2

我正在使用引导弹出模式窗口,并尝试 $emit 和事件,但由于某种原因,主页没有检测到事件。这是一个非常简单的设置,但我不知道为什么。从我在查看 Batarang 时所知道的情况来看,弹出窗口似乎是主应用程序范围的子范围,所以我认为它可以工作,但它没有。在这个简单的应用程序中,当您在弹出窗口中按“确定”时,它应该在父范围中设置一个值。这是一个笨蛋:

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;
        });

谢谢!

4

1 回答 1

5

我不确定传递$scope给服务是否是个好主意。$scope与它在视图中的放置位置非常相关,所以你真的知道是应该$emit还是应该$broadcast?此外,当您通过$scope. 相反,传递一个回调函数。

话虽如此,您正在调用$emit指令$modal的范围,该范围可能是一个孤立的范围(我不知道该指令是如何定义的),因此它永远不会到达父级。

所以你可以这样做:

parentScope.$emit('ModalSelect', 'hello world');

或者,您可以使用$rootScope

$scope.$root.$broadcast('ModalSelect', 'hello world');
于 2014-12-03T01:09:38.580 回答