AngularJS passing data back from mdDialog to parent controller

前端 未结 2 826
旧巷少年郎
旧巷少年郎 2021-01-23 10:18

I have a little Angularjs application making use of $mdDialog to pop up a html page that has one text input on it

I want to be able to return the value the user types in

2条回答
  •  长发绾君心
    2021-01-23 10:34

    While this wouldn't be right before the dialog closed, I would probably do this using the .then part of the dialog.show promise. Here is a codepen with using one of the ngMaterial examples to modify a variable on close: https://codepen.io/mckenzielong/pen/veBrgE. Basically, something like this:

    $scope.showNewTeamDialog = function () {
       $mdDialog.show({
           controller: NewTeamDialogController,
           templateUrl: 'NewTeam.html',
           locals: { newTeamName: $scope.newTeamName },
           parent: angular.element(document.body)
       })
       .then((newTeamName) => {
         $scope.newTeamName = newTeamName;
       })
    };
    
    function NewTeamDialogController($scope, $mdDialog, newTeamName) {   
      $scope.closeDialog = function(newTeamName) {
        $mdDialog.hide(newTeamName);
      }  
    }
    

    Alternatively you could do something a little more ugly, and share the scope like this: https://codepen.io/mckenzielong/pen/zEOaRe. One downside to this is your code will become confusing very quickly. Something like this:

    $scope.showNewTeamDialog = function () {
       $mdDialog.show({
           controller: NewTeamDialogController,
           templateUrl: 'NewTeam.html',
           scope: $scope.newTeamName,
           parent: angular.element(document.body)
       })
       .then(() => {
    
       })
    };
    
    function NewTeamDialogController($scope, $mdDialog) {   
      $scope.closeDialog = function(newTeamName) {
        $scope.newTeamName = newTeamName
        $mdDialog.hide();
      }  
    }
    

提交回复
热议问题