简体   繁体   中英

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. 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. 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? If so, then you would need to create your directive like this (assuming you named our outer controller 'Ctrl'). Notice the Ctrl. in front of 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. You should create a constructor:

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

And call the method from the $scope like so:

this.$scope.onSuccessCallback();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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