Search code examples
angularjstypescriptangular-directive

Service to communicate between parent directive and all children, 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.

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?

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


Solution

  • 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'
    

    In child's directive

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

    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.

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