-1

I have a mdDialog inside of my application that makes a call to an API which responds with some data. I need this data response to be accessible in the main controller so that it can be used in another call.

CRUD operation

 $scope.add_id = [];
    $scope.createAddress = function() {
        $http.get('api.php?action=create-address', {
            params: {
                add1: $scope.newadd.add1,
                add2: $scope.newadd.address2,
                city: $scope.newadd.city,
                state: $scope.newadd.state,
                zip: $scope.newadd.zip
            }
        })
        .success(function(response) {
            $scope.add_id = response.data[0].address_id;
        });
    };

mdDialog

$scope.addParcel = function(ev) {
    $mdDialog.show({
        controller: DialogController,
        templateUrl: 'libs/html/addparcel.html',
        parent: angular.element(document.body),
        targetEvent: ev,
        clickOutsideToClose:true,           
        scope: $scope,
        preserveScope: true            
    });
};

So inside of the addParcel mdDialog I have a button that executes the addAddress function and it turns successful and I can access the data within the dialog. However, even though the dialog is set to preserve the scope, the address_id does not appear at all in the main controller after I close the dialog. Am I supposed to use locals? How can I get the data to be accessible in the main controller? Please be as informative as possible as I am still new to AngularJS. Thanks.

gnomes
  • 39
  • 1
  • 5
  • 1
    to start with, [don't use `.success`](http://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6). – Claies Apr 17 '17 at 15:23

1 Answers1

0

It's because mdDialog creates a new child scope that inherits from your page controller's $scope.

You could do a couple of things,

  1. create an object in your page controller, something called "addressDetails", and access that in your addAddress function

    // Page Controller $scope.addressDetails = {};

    // addAddress $http.get(...).then(function (response) { $scope.addressDetails.add_id = response.data[0].address_id; });

  2. use $scope.$parent (not recommended)

You can read this wiki about scope inheritance (it's a great article)

https://github.com/angular/angular.js/wiki/Understanding-Scopes

agadzik
  • 41
  • 1
  • 7