A little more elaboration:
Say I have a service:
app.service('MyService', function(SomeWebSocketService) {
function MyService() {
this.object = {};
}
MyService.prototype.subscribe = function() {
var self = this;
SomeWebSocketService.subscribe('someTopic', function(data) {
angular.extend(self.object, data);
}
}
return MyService;
}
// usage
app.controller('MyController', function($scope, MyService) {
var model = new MyService();
$scope.object = model.object;
});
When I get messages from the WebSocket service, I'd like the $digest
loop to trigger. My first inclination was to do something like this:
app.service('MyService', function(SomeWebSocketService) {
function MyService(scope) {
// scope from wherever this service was called
this.scope = scope;
this.object = {};
}
MyService.prototype.subscribe = function() {
var self = this;
SomeWebSocketService.subscribe('someTopic', function(data) {
angular.extend(self.object, data);
self.scope.$apply();
}
}
return MyService;
}
// usage
app.controller('MyController', function($scope, MyService) {
var model = new MyService($scope);
$scope.object = model.object;
});
But I don't like having to pass in some arbitrary scope. So I thought of doing this:
app.service('MyService', function($rootScope, SomeWebSocketService) {
function MyService() {
this.object = {};
}
MyService.prototype.subscribe = function() {
var self = this;
SomeWebSocketService.subscribe('someTopic', function(data) {
angular.extend(self.object, data);
$rootScope.$apply();
}
}
return MyService;
}
// usage
app.controller('MyController', function($scope, MyService) {
var model = new MyService();
$scope.object = model.object;
});
Will I take a performance hit for doing this? Or is calling $apply
on one $scope
the same as calling $apply
on any?