如何在控制器和 $mdDialog 之间共享作用域?

How to share scope between controller and $mdDialog?

如何在控制器和 $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
    })
}

};

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

The bind() method creates a new function that, when called, has its this keyword set to the provided value

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),

   }
})

在你的控制器中:

.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>

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