简体   繁体   English

TypeScript中带有函数参数的Angular指令

[英]Angular directive with function parameter in TypeScript

I'm trying to add an Angular function parameter to a directive written in TypeScript but I must not have the syntax right. 我试图将Angular函数参数添加到用TypeScript编写的指令中,但是我必须没有语法权利。 Here is an example of my directive: 这是我的指令的示例:

export class NewUserDirective implements ng.IDirective {
    public restrict: string = "E";
    public replace: boolean = true;
    public templateUrl: string = '/views/_dialogs/newUserDialog.html';
    public controller = Directives.NewUserController;
    public controllerAs: string = 'Ctrl';
    public bindToController: boolean = true;
    public scope: any = {
        showDialog: '=',
        saveInProgress: '=',
        onSuccessCallback: '&',
        onClosingCallback: '&'
    };
}

and here is a snippet of my controller: 这是我的控制器的片段:

export class NewUserController {
    static $inject = ["$scope", "$q", "UserServices"];

    public showDialog: boolean;
    public saveInProgress: boolean;
    public onSuccessCallback: () => void;
    public onClosingCallback: () => void;

....

    public save(): void {

        //Flag as saving
        this.saveInProgress = true;

        //Save the plan
        this.UserServices.createUser(this.newUser).then(x => {

            //When finished, hide the modal
            this.showDialog = false;

            //Let parent know new user is created
            this.onSuccessCallback();
        });
    }

}

Everything is working except for the function parameter in the parent controller. 除了父控制器中的function参数,其他所有东西都可以正常工作。 I've tried a few different syntaxes in the directive implementation like this: 我在指令实现中尝试了几种不同的语法,如下所示:

    <new-user-directive on-success-callback="loadData()" ...

and this: 和这个:

    <new-user-directive on-success-callback="loadData" ...

Are you using controllerAs for the outer controller that has the loadData method on it? 您是否将controllerAs用于具有loadData方法的外部控制器? If so, then you would need to create your directive like this (assuming you named our outer controller 'Ctrl'). 如果是这样,那么您将需要像这样创建指令(假设您将外部控制器命名为“ Ctrl”)。 Notice the Ctrl. 注意Ctrl. in front of loadData() loadData()前面

<new-user-directive on-success-callback="Ctrl.loadData()" ...

您具有controllerAs =' Ctrl ',因此on-success-callback =“ Ctrl .loadData()”

The methods are passed through the $scope and not on the controller. 这些方法通过$ scope传递,而不是通过控制器传递。 You should create a constructor: 您应该创建一个构造函数:

constructor(private $scope, ....){
}

And call the method from the $scope like so: 然后像这样从$ scope调用方法:

this.$scope.onSuccessCallback();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM