【问题标题】:Receiving bound event from component inside component or mdDialog从组件或 mdDialog 内部的组件接收绑定事件
【发布时间】:2017-04-24 02:37:00
【问题描述】:

使用 Angular 1.5 和 Material Design,我创建了一个组件,它代表一个用于创建 foobar 的面板,带有一个“取消”按钮。显然面板不知道它是否在对话框中,所以“取消”按钮只是调用一个回调。具体来说,“取消”按钮调用控制器的cancel() 方法,然后尝试调用oncancel() 回调:

angular.module("NewFooBarPanel", [])
    .component("newFoobarPanel", {
        templateUrl: "newfoobar-template.html",
        bindings: {
            onCancel: "&"
        },
        controller: function() {
            var controller = this;

            controller.cancel = function() {
                controller.clearForm();
                controller.onCancel({});
            }

在封闭组件中,当单击 FAB 时,我会弹出一个 mdDialog;该对话框包含 newFoobarPanel:

angular.module("FoobarList", ["NewFooBarPanel"])
    .component("foobarList", {
        templateUrl: "foobarlist-template.html",
        controller: function($mdDialog) {

            this.addFoobar = function(ev) {

                $mdDialog.show({
                        template: "<md-dialog aria-label='Add Foobar'><new-foobar-panel on-cancel='alert(\"need to cancel\")'></new-foobar-panel></md-dialog>",
                        targetEvent: ev,
                        clickOutsideToClose: true,
                        fullscreen: true
                    });

当我单击取消按钮时,表单被清除,因此我知道 newFoobarPanel 控制器的 cancel() 方法正在被调用。但我没有看到警报对话框,因此由于某种原因,&lt;new-foobar-panel on-cancel='alert(\"need to cancel\")'&gt;&lt;/new-foobar-panel&gt; 中的 on-cancel 回调似乎没有被调用。

这是一个复杂的东西(尽管它是一个简单、直接的用例),其中一个组件位于组件内部的对话框中。我似乎已经将问题缩小到回调的调用。我哪里做错了?

所以我决定完全取消 mdDialog。现在我简单地将 newFoobarPanel 直接嵌入到 foobarList 组件中:

<new-foobar-panel on-cancel='alert("need to cancel")'></new-foobar-panel>

现在这只是组件中的一个组件,但我仍然没有看到警报对话框。为什么没有调用回调?

【问题讨论】:

    标签: angularjs callback angular-material angular-components


    【解决方案1】:

    原来问题不在于没有调用回调。问题是如何识别它。显然alert() 在这种情况下不起作用。

    所以我不得不向 mdDialog 添加一个控制器,并向$scope 添加一个方法来接收回调:

                    $mdDialog.show({
                            controller: function($scope, $log) {
                              $scope.notify=function() {
                                $log.debug("need to cancel");
                              }
                            },
                            template: "<md-dialog aria-label='Add Foobar'><new-foobar-panel on-cancel='notify()'></new-foobar-panel></md-dialog>",
                            targetEvent: ev,
                            clickOutsideToClose: true,
                            fullscreen: true
                        });
    

    现在,当嵌入式组件调用回调时,对话框控制器会记录一条消息!太好了!

    如果有更好的方法在这里添加控制器方法(我可以依靠this吗?)而不是注入$scope,请告诉我。

    (现在我需要弄清楚如何从它的控制器中关闭 mdDialog,但这是一个单独的问题。)

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 2016-07-10
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 2017-04-13
      相关资源
      最近更新 更多