【问题标题】:How to call function on controller with Angular Material Dialog如何使用 Angular Material Dialog 在控制器上调用函数
【发布时间】:2023-04-07 07:48:01
【问题描述】:

我有一个基于 Angular 1.5 typescript 的应用程序,使用 angular material。

如何从 Dialog 调用控制器中的函数?

在我的示例中,我想在用户确认后调用 this.callBack()

代码sn-p

 public delete(condition: ModelModule.Condition): void {
        var confirm = this.$mdDialog.confirm()
            .title('delete condition!')
            .textContent('are you sure ?')
            .ariaLabel('delete')
            .ok('Ok')
            .cancel('Cancel');

        this.$mdDialog.show(confirm).then(function(answer) {
             console.log("You decided to delete "+answer)
        // how to call this function on my controller ???              
        this.callBack()

        }, function() {
            console.log("You decided cancel")
        });
    }

【问题讨论】:

  • 这里有什么问题?对我来说,您发布的代码似乎可以正常工作
  • 它失败了:angular.js:14110 TypeError: Cannot read property 'callBack' of undefined
  • 我自己找到了解决方案。通过将“this”复制到您自己的语言环境变量开始函数调用 // 复制到变量,否则无法调用其他函数 var that = this; ...其余功能

标签: angularjs angular-material


【解决方案1】:

您的this 指的是function,而不是您的控制器。不要在 Typescript 中使用function,而是使用箭头函数,它不会创建新的 this-context。

public delete(condition: ModelModule.Condition): void {
    var confirm = this.$mdDialog.confirm()
        .title('delete condition!')
        .textContent('are you sure ?')
        .ariaLabel('delete')
        .ok('Ok')
        .cancel('Cancel');

    this.$mdDialog.show(confirm).then((answer) => {
         console.log("You decided to delete " + answer);
         this.callBack();
    }, () => {
        console.log("You decided cancel");
    });
}

this in Typescript

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2019-11-08
    • 2018-04-13
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多