[英]Call a function within a TypeScript Angular directive?
For a while now, I've been following an Angular directive TypeScript pattern that I really like. 有一段时间了,我一直在关注我非常喜欢的Angular指令TypeScript模式。 I give the directive its own isolated
scope
by creating a new controller. 我通过创建一个新的控制器给指令自己的孤立
scope
。
I've run into a situation where I need to call a function within my Angular directive from outside of the directive. 我遇到了一种情况,我需要在指令之外的Angular指令中调用一个函数。
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. 有了一些非常基本的CSS,这就像一个魅力。 But, what if I have a controller that creates this directive, and wants to trigger the directive's
openPopup
function. 但是,如果我有一个创建该指令的控制器,并希望触发该指令的
openPopup
函数,该怎么办? 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?
有什么建议么?
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. 在这种情况下我要做的是在你的指令中添加一个“isOpen”属性,并从
ng-click
调用中切换该值true / false。
It would look like this in your HTML: 在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.