angularjs从服务发送消息 [英] angularjs send message from service
问题描述
我有创造了外部组件的配置对象的服务。
其中一个配置属性是一个可选功能,当一些事件(无角)被触发时调用。
例如。
{
事件处理程序:功能(E){...}
}
这里面事件处理程序我想将消息发送到电流控制器。
我试图获得$ rootService的实例,但它不知道$播出。
更新:code(简化版,保持code短)
app.service('componentService',['$ rootScope',
功能($ rootScope){
this.getConfig =功能(){
返回{
过渡:真实,
... //其他配置参数
clickHandler事件:功能(E){//事件由外部库,E =事件参数称为
$ rootScope $广播(myEvent,e.value)。
};
};
返回{
getConfig:this.getConfig
}
}]);
的http:/ /plnkr.co/edit/BK4Vjk?p=$p$pview
看看我上面所做的例子。它应该工作。
有在你的code的片断几个语法错误。我不知道这是否是因为你只是快速地打字,或如果他们真的存在。
基本上是:
app.controller('MainCtrl',函数($范围,componentService){
变种配置= componentService.getConfig();
$('#nonAngular')绑定(点击,config.clickHandler)。
$范围。在$('myEvent',函数(即价值){
的console.log('这是角事件',E);
的console.log('这就是价值,价值)
});
});app.service('componentService',['$ rootScope',
功能($ rootScope){
this.getConfig =功能(){
返回{
过渡:真实,
clickHandler事件:功能(E){//事件由外部库,E =事件参数称为
$ rootScope $广播(myEvent,你传递到赛事转播的一些值)。
}
}
}
}]);
I have a service which creates a configuration object for an external component. One of the config properties is an optional function that gets called when some event (non angular) gets triggered.
e.g. { eventHandler:function(e) { ... } }
Inside this eventhandler I want to send a message to the current controller. I tried getting instance of $rootService but it doesn't know about $broadCast.
update : the code (simplified version, to keep code short)
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
}
}]);
http://plnkr.co/edit/BK4Vjk?p=preview
Check out the example I made above. It should work.
There's a few syntax errors in your snippet of code. I wasn't sure if it was because you were just quickly typing it or if they're really there.
Basically:
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");
}
}
}
}]);
这篇关于angularjs从服务发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!