Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

For a while now, I've been following an Angular directive TypeScript pattern that I really like. I give the directive its own isolated scope by creating a new controller.

I've run into a situation where I need to call a function within my Angular directive from outside of the directive.

For example, I have a really simple function that opens a popup within my directive. The directive's controller has something like:

public openPopup() {
    this.uiClasses.popup = "open";
}

The corresponding view has a few notable elements like:

<div ng-click="vm.openPopup()">Open the pop up</div>
<div ng-class="vm.uiClasses.popup">the actual popup</div>

With some really basic CSS, this works like a charm. But, what if I have a controller that creates this directive, and wants to trigger the directive's openPopup function. I want to do something like this:

class PageController {
    private scope: any = null;
    static $inject = ["$scope"];

    constructor($scope: any) {
        $scope.vm = this;
    }

    public openTheDirectivePopup() {
        // from here, how can I call the openPopup on a specific directive?
    }
}

The corresponding view:

<div ng-click="vm.openTheDirectivePopup()">I can open the popup inside the custom directive</div>
<my-custom-directive></my-custom-directive>

I also want to be able to have multiple instances of these directives on the same page without conflict.

It seems like this should be do-able, but I can't quite wrap my head around it. Any suggestions?

share|improve this question
up vote 0 down vote accepted

What I would do in that case is add a "isOpen" attribute to your directive, and toggle that value true / false from your ng-click call.

It would look like this in your HTML:

<div ng-click="vm.isOpen = true">I can open the popup inside the custom directive</div>
<my-custom-directive isOpen="vm.isOpen"></my-custom-directive>
share|improve this answer
    
That would certainly be a way to solve the actual problem I have - but, my question is actually about calling the function within the directive. Is this possible? Or would this approach be the only way to do something similar? – amlyhamm Aug 27 '15 at 18:06
    
You would need a service to expose some of the logic to the outside. What I showed you is the most common way to achieve what you're trying to do. – alcfeoh Aug 27 '15 at 18:08
    
Awesome - that's exactly what I wanted to know. Thanks, @alcfeoh – amlyhamm Aug 28 '15 at 15:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.