Reputation: 1150
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?
Upvotes: 3
Views: 2044
Reputation: 2267
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>
Upvotes: 0