someChildScope有什么区别。$ apply()和$ rootScope。$ apply()?

时间:2014-07-08 01:04:56

标签: javascript angularjs

更详细一点:

说我有服务:

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一样?

0 个答案:

没有答案