Javascript 在angular中广播事件:如何通过订阅事件来改变流?
我的程序中有以下逻辑:Javascript 在angular中广播事件:如何通过订阅事件来改变流?,javascript,angularjs,Javascript,Angularjs,我的程序中有以下逻辑: 用户点击一些按钮 模式对话框出现 一旦它关闭,promise就会返回(我使用angular bootstrap中的$modal)并执行一些操作 因此,这是$modal的简单调用: var modalInstance = $modal.open({ // here goes modal configuration }); modalInstance.result.then(function (chosenProj
var modalInstance = $modal.open({
// here goes modal configuration
});
modalInstance.result.then(function (chosenProject) {
// some action on data returned from modal
})
我需要的是在我即将从#2打开该对话框之前广播一个事件。订阅该事件的“中介”代码应影响#2-3处的操作,即能够阻止执行这些步骤。因此,我愿意有这样的执行计划:
$rootScope.$broadcast("aboutToOpenDialog");
/// !!! Then I need some function to listen to the event, make decision, return some data,
/// and I want then use that data to decide, if I open dialog or not:
var modalInstance = $modal.open({
// here goes modal configuration
});
modalInstance.result.then(function (chosenProject) {
// some action on data returned from modal
})
如何使用angular编写这样的事件驱动序列?您可以使用
$event
对象来实现您想要的
广播时,将创建一个$event
对象并发送给所有侦听器。您有机会将任何想要的返回值存储到某个侦听器中的$event
对象中(或使用内置的preventDefault()
机制),如下所示:
$scope.$on('aboutToOpenDialog', function ($event) {
// you could use built-in preventDefault() and defaultPrevented
if ($scope.noModal) {
$event.preventDefault();
}
// or just assign any values to some property and get it back later.
$event.someReturnValue = $scope.noModal ? 'noModal' : 'showModal';
});
当广播结束时,$broadcast()
将返回相同的$event
对象,您可以检查该对象上的值
$scope.openDialog = function() {
var $event = $rootScope.$broadcast("aboutToOpenDialog");
if (!$event.defaultPrevented) {
// $modal.open() here
console.log('open modal');
} else {
console.log('suppress modal');
}
// or
if ($event.someReturnValue === 'showModal') {
// $modal.open() here
console.log('open modal again');
}
};
示例plunker:
希望这能有所帮助。请包含一些您当前拥有的代码或您所做的任何让您陷入困境的尝试。目前这是一个非常模糊的问题,不太可能给出充分的答案。@第四,初始序列的代码非常简单,是引导$model的文本副本,上面有$scope.$broadcast。第二部分的代码是我正在寻找的。我一直关注的是如何让事情在架构逻辑层面上运行。源代码一点也不会增加它的清晰度(尽管在心理上令人放心)。