xro*_*kam 5 service events controller angularjs
我想以角度创建自定义事件.目标是该事件将由服务广播,并且必须在控制器中捕获.
我有我的服务:
function doSomething() {
// do something...
$rootScope.$broadcast("bced");
$rootScope.$emit("emitted");
console.log('event');
}
Run Code Online (Sandbox Code Playgroud)
和我的控制器:
$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");
});
Run Code Online (Sandbox Code Playgroud)
但我无法捕捉到控制器中的事件.显示console.log('event')但我无法捕获任何事件.有人可以解释一下如何做到这一点吗?$ rootScope在服务和控制器中正确声明.
Iva*_*aev 11
查看工作演示:
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;
})
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6828 次 |
| 最近记录: |