Search code examples
angularjsangularjs-directiveangular-directive

angular directives - Parent calls children isolated scope method


In my angular app I've got a parent directive, say a list of some sort, that contains many child directives, say items.

I'd like to be able to call a certain method on the children from the parent. I know in advance what children I'd be calling (by an input of start and end index of the items list). Therefore I wish to avoid using broadcast, as I don't want to call all children but just a selected few.

Both the children and the parent have their own isolated scopes.

How can I achieve this?


Solution

  • Try to create controllers for your parent directive. That is accessible for your children directives, it's some kind of shared functions for your children directives. Then you can register a function which can add new functions to the parent controllers that u can later execute. Let me show you with a quick example (maybe it won't work with copy-paste, its just the theory how should it look like)

    //parent directive's controller function
    function ParentControllerFunction(){
        this.arrayOfChildFuncions = [];
    }
    
    //your child directive's link function
    require: '^ParentControllerFunction'
    link: function(scope, element, attr, ctrl){
        function myLittleFunction(){
           //hhere is your function that you can call
        }
    
        ctrl.arrayOfChildFuncions.push(myLittleFunction);
    }
    

    Then later on you can execute your functions depending on which one do you want to:

    //executes the 3rd directive's function with the parameter 'hello'
    arrayOfChildFuncions[3]('hello')