0

In my angular project I'm using Angular.js material. And I want to show $mdialog with custom controller, where user changes some data and this data should be applied to my $scope variable. Example what I do now:

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;
     };
}

Then in dialog controller I do:

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

But I think it is the wrong way. So what is the best way to communicate between two view controllers in angular without new service ? Or better create another service like: EditDialogService, where I will save results ?

3 Answers 3

3

When you open a modal, the show() function returns a promise.

$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
   });
 }

Your modal controller can be injected with $mdDialog.

function editProfileViewCtrl($scope, name, $mdDialog) {
    $scope.close = function() {
        $mdDialog.hide('newName');
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

ah, sorry. Found it ! A promise that can be resolved with $mdDialog.hide() or rejected with $mdDialog.cancel(). Thanks
-1

You should create a directive with your user as scope variable. Angular in itself is handling the data binding.

Comments

-1

It is possible to create a minimal controller function that has access to $scope.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.