是否有一个孩子控制器继承服务&QUOT的方式;喜欢"例如从其父? [英] Is there a way for a child controller to inherit a service "like" instance from its parent?

查看:211
本文介绍了是否有一个孩子控制器继承服务&QUOT的方式;喜欢"例如从其父?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我有窗口实例。该应用程序可以包含多个窗口和窗口可以包含多个视图。该意见是每个窗口实例的孩子。

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

演示

这篇关于是否有一个孩子控制器继承服务&QUOT的方式;喜欢"例如从其父?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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