angularjs:来自服务的广播事件 [英] angularjs: broadcast event from service

查看:53
本文介绍了angularjs:来自服务的广播事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在angularjs中创建一个自定义事件.目标是该事件将由服务广播,并且必须在控制器中捕获.

I would like to create a custom event in angularjs. The goal is that the event will be broadcast by a service and must be catched in a controller.

我在为我服务:

function doSomething() {
        // do something...
        $rootScope.$broadcast("bced");
        $rootScope.$emit("emitted");
        console.log('event');
}

和我的控制器:

$rootScope.$on("bced",function(){
    console.log("catched");
});
$rootScope.$on("emitted",function(){
    console.log("catched");
});

$scope.$on("bced",function(){
    console.log("catched");
});
$scope.$on("emitted",function(){
    console.log("catched");
});

但是我无法在控制器中捕获事件.显示了 console.log('event'),但我无法捕获任何事件.有人可以解释一下该怎么做吗?在服务和控制器中正确声明了 $ rootScope .

But I can't catch events in controller. console.log('event') is shown but I can't catch any events. Could someone explain me how to do that please? $rootScope is correctly declared in the service and in the controller.

推荐答案

签出有效的演示:

var app = angular.module('core', []);
    app.service('SomeService', function($timeout, $rootScope){
        this.generateEvent = function(){
            $timeout(function(){
                $rootScope.$broadcast('event:show', {some: 'data'});
            }, 3000);    
        }
        
    })
    
    app.controller('MainController', function($scope, SomeService){
        SomeService.generateEvent();
        $scope.$on('event:show', function(event, data){
            $scope.test = data.some;
        })
    })

<div ng-app="core" ng-controller="MainController">
    {{test}}
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

这篇关于angularjs:来自服务的广播事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆