AngularJs - 为什么 $emit 在我的弹出窗口中不起作用

标签 angularjs emit

我正在使用引导弹出模式窗口,并尝试 $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;
        });

谢谢!

最佳答案

我不确定将 $scope 传递给服务是否是一个好主意。 $scope 与它在 View 中的放置位置密切相关,因此您真的知道是否应该 $emit 还是 $broadcast 吗?此外,当您传递 $scope 时,单元测试会变得更加困难。相反,传递一个回调函数。

话虽这么说,您正在 $modal 指令的作用域上调用 $emit,这可能是一个隔离的作用域(我不知道该指令是如何定义的) )所以它永远不会到达父级。

所以你可以这样做:

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

或者,您可以使用$rootScope:

$scope.$root.$broadcast('ModalSelect', 'hello world');

关于AngularJs - 为什么 $emit 在我的弹出窗口中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27261626/

相关文章:

forms - AngularJs 提交表单并重置 $pristine 状态

jquery - popconfirm 在表 (<td>) 中不起作用

javascript - 使用 $scope.$emit() 在组件之间传递数据

javascript - 我正在使用 Vue.js 2.0,我正在尝试从 `child component` 发出一个事件

python - 从 CSV 加载数据时,QAbstractListModel 不会更新值,但在使用硬编码值时会更新

javascript - socket.io 发射三次

map - 为什么发出(meta.id,NULL)

javascript - 保存全局变量以供观看的指令的最佳方法

javascript - 在 Angular 中使用 Http get 服务

javascript - $q.when 不是函数?