2016-04-07 121 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

相關問題