服务于母公司的指令和所有的孩子,angularjs之间进行通信 [英] Service to communicate between parent directive and all children, angularjs

查看:115
本文介绍了服务于母公司的指令和所有的孩子,angularjs之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我打算包含许多其他指令的指令,而且我打算有一些页面上的实例。我希望能够创建一个非单服务,我可以创建父指令一个新的实例,然后将其提供给所有的子指令在树中,使这些孩子能够影响父母的指令的行为。同时,对于一个父指令该服务不能修改其他亲指示和应该是唯一的,以它最初在实例化所述一个

I have a directive that I'm intending to contain a number of other directives and that I intended to have a number of instances of on the page. I would like to be able to create a non-singleton service that I can create a new instance of for the parent directive and then make it available to all child directives within that tree so that those children can influence the behavior of the parent directive. At the same time, the service for one parent directive cannot modify other parent directives and should be unique to the one it's originally instantiated in.

在理想情况下,我希望能够从每个子指令调用这个服务的功能,然后让它无论是与其他服务或直接与家长沟通的指令。但是,我知道,服务是单身,所以这里并不完全正确的术语。是否有其他AngularJS机制我可以用于此目的?

Ideally, I'd like to be able to call functions on this service from each of the child directives and then have it communicate either with other services or directly with the parent directive. However, I'm aware that services are singletons, so that's not quite the right terminology here. Is there another AngularJS mechanism I can use for this purpose?

此应用程序是用打字稿与AngularJS v1.4.7 - 感谢您的帮助

This application is written in TypeScript with AngularJS v1.4.7 - thanks for your help!

推荐答案

您可以创建在父指令的对象的实例,并把它传递给每个孩子在指令的属性。

You can create an instance of an object in the parent directive, and pass it to each children in the attribute of the directives.

class parentDirective {
    instanciatedService : MyService;
    constructor() {
        this.instanciatedService = new MyService();
    }
}

template : `
<parent>
    <child custom-service="vm.instanciatedService"></child>
</parent>
`,
controllerAs : 'vm'

在孩子的指令

bindToController /* or scope */ {
    customService: "="
},

在父母的指令,你实例化 instanciatedService ,然后孩子们和家长可以访问相同的对象。这是一种依赖注入throught指令属性。

In parent directive, you instanciate instanciatedService, then children and parent can access that same object. It's a kind of dependency injection throught directives attributes.

这将obvisouly导致更多的样板在HTML模板,但至少这不是一个单例。

This will obvisouly leads to more boilerplate in html templates, but at least this is not a singleton.

这篇关于服务于母公司的指令和所有的孩子,angularjs之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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