有没有办法让子控制器继承“喜欢"的服务?来自其父级的实例? [英] Is there a way for a child controller to inherit a service "like" instance from its parent?

查看:18
本文介绍了有没有办法让子控制器继承“喜欢"的服务?来自其父级的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有窗口实例.应用程序可以包含多个窗口,窗口可以包含多个视图.视图是每个窗口实例的子级.

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 windowController($scope, WindowService) {
    WindowService.setWindowConfig($scope.window);
}

function viewController($scope, WindowService) {
    WindowService.updateDirtyState(true);
}

我希望能够从视图更新窗口.但我只希望孩子们能够更新他们的父窗口.由于服务是单例,视图将更新所有窗口.

I want to be able to update the window from the view(s). But I only want the children to be able to update their parent window. Being that services are singletons, the view would update all windows.

有没有办法在不传递某种 ID 的情况下实现这一目标?

Is there a way to achieve this without passing some sort of ID around?

推荐答案

服务单例,但它们可以包含对象的构造函数,而不是它们返回的对象.

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 = {};

  var Window = function() {
    ...
  };

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

  var View = function(window) {
    this.window = window;
  };

  service.newWindow = function(){
    return new Window();
  }

  service.newView = function(){
    return new View(window);
  }

  return service;
});

假设每个 ViewController 都有自己的 WindowController 父级,它们可以这样实例化:

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);
})

没有理由担心 id,因为视图对象将包含对其窗口父项的引用.事实上,如果所有 ViewController 都有一个 WindowController 父级,您可以通过原型继承引用该范围变量,通过 $scope.window 从视图,绕过 WindowService 访问窗口对象.

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();
})

演示

这篇关于有没有办法让子控制器继承“喜欢"的服务?来自其父级的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆