【问题标题】:Call a function within a TypeScript Angular directive?在 TypeScript Angular 指令中调用函数?
【发布时间】:2015-11-22 05:57:39
【问题描述】:

一段时间以来,我一直在遵循我非常喜欢的 Angular 指令 TypeScript 模式。我通过创建一个新的控制器为指令提供了自己独立的scope

我遇到了一种情况,我需要从指令的外部调用 Angular 指令中的函数。

例如,我有一个非常简单的函数,可以在我的指令中打开一个弹出窗口。该指令的控制器类似于:

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

相应的视图有一些值得注意的元素,例如:

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

使用一些非常基本的 CSS,这就像一个魅力。但是,如果我有一个创建该指令的控制器,并且想要触发该指令的openPopup 函数,该怎么办。我想做这样的事情:

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?
    }
}

对应的视图:

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

我还希望能够在同一页面上拥有这些指令的多个实例而不会发生冲突。

看起来这应该是可行的,但我无法完全理解它。有什么建议吗?

【问题讨论】:

    标签: javascript angularjs angularjs-directive typescript


    【解决方案1】:

    在这种情况下,我会做的是在你的指令中添加一个“isOpen”属性,并从你的ng-click 调用中切换该值真/假。

    在您的 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>
    

    【讨论】:

    • 这肯定是解决我遇到的实际问题的一种方法 - 但是,我的问题实际上是关于在指令中调用函数。这可能吗?还是这种方法是做类似事情的唯一方法?
    • 您需要一个服务来向外部公开一些逻辑。我向您展示的是实现您想要做的最常见的方法。
    • 太棒了——这正是我想知道的。谢谢,@alcfeoh
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    相关资源
    最近更新 更多