从angularjs服务呼叫控制器功能 [英] Call controller function from service in angularjs
问题描述
我使用socket.io启用聊天功能在我的应用程序,我使用的是服务 SocketService
来执行所有的插座的东西。当消息传来,然后我想从服务触发控制器的功能 SocketService
来使UI中的一些变化。
所以我想知道,我怎样才能从服务访问控制的功能。
示例code:
。服务('SocketService',函数($ HTTP,$ rootScope,$ Q){
this.connect =功能(){
变种插座= io的();
socket.on('连接',函数(){
//调用一个控制器中名为someFunction功能ChatController
});
}
});
这是样品code的服务。
现在的code为控制器
.controller('ChatController',函数('SocketService',$范围){
$ scope.someFunction =功能(){
//有些code这里
}
});
您可以通过使用角事件 $广播
或 $ EMIT <做到这一点/ code>。
在你的情况 $广播
将是有益的,
你需要在 $ rootscope
来播放您的活动可以由所有有子作用域可以听 $关于
与相同活动名称。
code
。服务('SocketService',函数($ HTTP,$ rootScope,$ Q){
this.connect =功能(){
变种插座= io的();
socket.on('连接',函数(){
//调用一个控制器中名为someFunction功能ChatController
$ rootScope。$广播('eventFired',{
数据:'东西'
});
});
}
});
.controller('ChatController',函数('SocketService',$范围){
$ scope.someFunction =功能(){
//有些code这里
}
$范围。在$('eventFired',函数(事件数据){
$ scope.someFunction();
})
});
希望这可以帮助你,谢谢你。
I am using socket.io to enable chat in my app and i am using a service SocketService
to perform all the socket stuff. When a message came then i want to trigger a function of a controller from the service SocketService
to make some changes in the UI.
So i want to know that how can i access the function of a controller from the service.
Sample Code:
.service('SocketService', function ($http,$rootScope,$q) {
this.connect = function(){
var socket = io();
socket.on('connect',function(){
// Call a function named 'someFunction' in controller 'ChatController'
});
}
});
This is the sample code for service.
Now the code for controller
.controller('ChatController',function('SocketService',$scope){
$scope.someFunction = function(){
// Some Code Here
}
});
You could achieve this by using angular events $broadcast
or $emit
.
In your case $broadcast
would be helpful,
You need to broadcast your event in $rootscope
that can be listen by all the child scopes which has $on
with same event name.
CODE
.service('SocketService', function($http, $rootScope, $q) {
this.connect = function() {
var socket = io();
socket.on('connect', function() {
// Call a function named 'someFunction' in controller 'ChatController'
$rootScope.$broadcast('eventFired', {
data: 'something'
});
});
}
});
.controller('ChatController', function('SocketService', $scope) {
$scope.someFunction = function() {
// Some Code Here
}
$scope.$on('eventFired', function(event, data) {
$scope.someFunction();
})
});
Hope this could help you, Thanks.
这篇关于从angularjs服务呼叫控制器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!