Skip to content Skip to sidebar Skip to footer

Is There A Way For A Child Controller To Inherit A Service "like" Instance From Its Parent?

In my app I have window instances. The app can contain multiple windows and windows can contain multiple views. The views are children of each window instance. function windowContr

Solution 1:

Services are singletons, but they can contain constructors for objects other than the one they return.

Here is a skeleton example of a service which takes advantage of this fact:

.factory('WindowService', function(){
  var service = {};

  varWindow = function() {
    ...
  };

  Window.prototype.doSomething = function(){
    ...
  };

  varView = function(window) {
    this.window = window;
  };

  service.newWindow = function(){
    returnnewWindow();
  }

  service.newView = function(){
    returnnewView(window);
  }

  return service;
});

Assuming every ViewController has its own WindowController parent, they could be instantiated this way:

.controller('WindowController', function($scope, WindowService){
  $scope.window = WindowService.newWindow();
})
.controller('ViewController', function($scope, WindowService){
  $scope.view = WindowService.newView($scope.window);
})

There is no reason to worry about id's since the view objects will contain references to their window parents. In fact, if all ViewControllers have a WindowController parent, you could reference that scope variable through prototypical inheritance, via $scope.window from the view, bypassing WindowService for window object access.

.controller('ViewController', function($scope, WindowService){
    $scope.view = WindowService.newView($scope.window);
    // don't need to do $scope.view.window.doSomething(), but you could$scope.window.doSomething();
})

Demo

Post a Comment for "Is There A Way For A Child Controller To Inherit A Service "like" Instance From Its Parent?"