我有一个为外部组件创建配置对象的服务。配置属性之一是一个可选函数,当某个事件(非角度)被触发时会被调用。
例如 { eventHandler:function(e) { ... } }
在这个事件处理程序中,我想向当前控制器发送一条消息。我尝试获取 $rootService 的实例,但它不知道 $broadCast。
更新:代码(简化版,保持代码简短)
app.service('componentService',['$rootScope',
function($rootScope) {
this.getConfig = function() {
return {
transition:true,
... // other config parameters
clickHandler:function(e) { // event called by external library, e = event args
$rootScope.$broadCast("myEvent",e.value);
};
};
return {
getConfig : this.getConfig
}
}]);
Run Code Online (Sandbox Code Playgroud)
http://plnkr.co/edit/BK4Vjk?p=preview
看看我上面做的例子。它应该工作。
您的代码片段中有一些语法错误。我不确定是不是因为你只是快速输入,或者他们是否真的在那里。
基本上:
app.controller('MainCtrl', function($scope, componentService) {
var config = componentService.getConfig();
$('#nonAngular').bind('click', config.clickHandler);
$scope.$on('myEvent', function(e, value) {
console.log('This is the angular event ', e);
console.log('This is the value ', value)
});
});
app.service('componentService',['$rootScope',
function($rootScope) {
this.getConfig = function() {
return {
transition:true,
clickHandler:function(e) { // event called by external library, e = event args
$rootScope.$broadcast("myEvent", "Some value you're passing to the event broadcast");
}
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3777 次 |
| 最近记录: |