我想以角度创建自定义事件.目标是该事件将由服务广播,并且必须在控制器中捕获.
我有我的服务:
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在服务和控制器中正确声明.
解决方法
查看工作演示:
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>