【问题标题】:How to share scope between controller and $mdDialog?如何在控制器和 $mdDialog 之间共享范围?
【发布时间】:2016-04-07 01:41:49
【问题描述】:

如何在控制器和 $mdDialog (Angular Material) 之间共享范围? 我正在使用“Controller As”语法,我需要在 $mdDialog 中使用控制器的功能,因为当它关闭时,我需要一些数据。 在这段代码中,我需要在 $mdDialog 中调用“myFunction”。 如果我有一个对象 (self.obj) 并且我需要将它放入“myFunction”中,则会发生这种情况,当 $mdDialog 调用“myFunction”时,该对象不存在于范围内。

angular.module('myApp')
          .controller('myController', myController);

myController.$inject = ['$mdDialog'];

function myController($mdDialog) {

var self = this;
self.obj = {'firstName:'hello','lastName':'world'}


self.myFunction = function () {console.log(JSON.stringfy(self.obj))};

self.showDialog = function (){

    $mdDialog.show({
        controller: function ctrl() {},
        controllerAs: 'ctrl',
        templateUrl: 'views/modal_templates/dialog01.template.html',
        parent: angular.element(document.body),
        targetEvent: ev,
        clickOutsideToClose: true
    })
}

};

【问题讨论】:

    标签: angularjs angular-material


    【解决方案1】:

    在您的控制器中:

    .controller('testing',
            function($scope,  $mdDialog) {
     $scope.items = [0, 1, 2, 3];
        $scope.addAddress = function(ev)
        {
            $mdDialog.show({
                controller: () => this,
                  controllerAs: 'ctrl',
                  templateUrl: 'views/address.html',
                  targetEvent: ev,
                  clickOutsideToClose:true,
                  locals: {
                      items: $scope.items,
                   },
                   });
        };
    

    在 address.html 中,使用 'ctrl' 访问项目

    <din ng-repeat="items in ctrl.items">
    {{ items }}
    </div>
    

    我从以下链接获得了这个解决方案: https://github.com/angular/material/issues/1531

    【讨论】:

      【解决方案2】:

      您可以使用 locals 选项来注入 myFunction。然后使用bind() 方法创建一个新函数,并将其 this 关键字设置为 self。

      bind() 方法创建一个新函数,在调用该函数时,其 this 关键字设置为提供的值

      self.myFunction = function () {console.log(JSON.stringfy(this.obj))};
      
      $mdDialog.show({
          controller: function ctrl(myfunction) { },
          controllerAs: 'ctrl',
          templateUrl: 'views/modal_templates/dialog01.template.html',
          parent: angular.element(document.body),
          targetEvent: ev,
          clickOutsideToClose: true,
          locals: {
             myfunctiion: myFunction.bind(self),
      
         }
      })
      

      【讨论】:

      • 感谢觉醒字节,我已经编辑了我的问题以便更好地解释。我的问题是我需要一个在“myFunction”中的对象,并且我将在我的模态模板上的 md 按钮中更新这个对象。
      • 更新了答案。您需要使用 bind() 方法将上下文锁定为 self
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      相关资源
      最近更新 更多