gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:12:34 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com