2017-10-17 137 views
0

在我的角度項目中,我使用Angular.js material。我想要顯示$mdialog與自定義控制器,其中用戶更改一些數據,這些數據應該適用於我的$scope變量。比如我現在做的事:Angular.js從另一個控制器回調

function myControllerFn($scope, MyService){ 
    // I do copy of my service variable because I don't want to change it until user will click save button 
    $scope.name = angular.copy(MyService.name); 

    $scope.editCurrentProfile = function() { 
     $scope.showEditProfileDialog($scope.name).then(function(name){ 
        $scope.name = name; 
     } 
    } 

    $scope.showEditProfileDialog = function(name) { 
     var deferred = $q.defer(); 
     $mdDialog.show({ 
     controller: 'editProfileViewCtrl', 
     templateUrl: 'controllers/editProfileDialog.tmpl.html', 
     locals: { 
      name: name, 
      deferred: deferred 
     } 
     }); 
     return deferred.promise; 
    }; 
} 

然後在對話框控制我做的:

function editProfileViewCtrl($scope, name, deffered) { 
    deferred.resolve('newName'); 
} 

但我認爲這是錯誤的方式。那麼在沒有新服務的情況下,兩個視角控制器之間以角度進行通信的最佳方式是什麼?或者更好地創建另一個服務,如:EditDialogService,我將保存結果?

回答

3

當您打開模式時,show()函數返回一個承諾。

$scope.showEditProfileDialog = function(name) { 
    var modalInstance = $mdDialog.show({ 
    controller: 'editProfileViewCtrl', 
    templateUrl: 'controllers/editProfileDialog.tmpl.html', 
    locals: { 
     name: name 
    } 
    }); 

    modalInstance.then(function(result){ 
     // acces what is returned 
     // In your case, you would do 
     $scope.name = result; 
    }, function(error){ 
     // Usually when you cancel your modal 
    }); 
} 

你的模態控制器可與$mdDialog注入。

function editProfileViewCtrl($scope, name, $mdDialog) { 
    $scope.close = function() { 
     $mdDialog.hide('newName'); 
    } 
} 
+0

怎麼樣錯誤(拒絕承諾)? – Arti

+1

啊,對不起。找到了 !可以使用$ mdDialog.hide()解決的承諾或使用$ mdDialog.cancel()拒絕的承諾。謝謝 – Arti

-1

您應該以您的用戶爲範圍變量創建指令。 Angular本身就是處理數據綁定。

-1

它可以創建一個具有訪問$範圍最小的控制器功能。

$mdDialog.show({ 
    controller: function() { this.parent = $scope; }, 
    templateUrl: 'controllers/editProfileDialog.tmpl.html', 
    locals: { 
    name: name, 
    deferred: deferred 
    } 
}); 
相關問題