2016-04-07 49 views
0

如何在控制器和$ mdDialog(角度材质)之间共享作用域? 我使用“控制器为”语法,我需要使用我的控制器的功能到$ 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 
    }) 
} 

}; 

回答

0

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

的bind()方法创建,当所谓的新功能,具有其将此关键字设置为所提供的值

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

    } 
}) 
+0

感谢觉醒字节,我已经编辑我的问题,以更好地解释。我的问题是我需要'myFunction'中的对象,并且我会在模态模板上的一个md按钮中更新这个对象。 –

+0

更新了答案。你需要使用bind()方法来锁定上下文到自我 –

+0

谢谢,它解决了我的问题。 –

2

在你的控制器:

.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

相关问题