更详细一点:
说我有服务:
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;
});
当我从WebSocket服务获取消息时,我希望触发$digest
循环。我的第一个倾向是做这样的事情:
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;
});
但我不想在某个任意范围内通过。所以我想到了这样做:
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;
});
这样做会让性能受到影响吗?或者在一个$apply
上拨打$scope
与在任何地方拨打$apply
一样?