简体   繁体   中英

How to pass data from inner controller of modal to outer controller in AngularJs

I'm trying to manipulate data inside a modal in AngularJS and after that, view it outside of the modal. So I have to pass the data from the inner controller (which is used by the modal) to the outer controller. To put the data into the inner controller from the outer one I've done this with help of the option resolve of $modal.open :

myApp.controller('MyCtrl', function ($scope, $modal) {

$scope.number = 1;

$scope.openModal = function () {
    $modal.open({
        templateUrl: 'myModalContent.html',
        backdrop: true,
        windowClass: 'modal',
        controller: function ($scope, $modalInstance, number) {
            $scope.number = number;
            $scope.submit = function () {

                //How to iterate var number in the outer controller?
                //$scope.number++;

                $modalInstance.dismiss('cancel');
            }
        },
        resolve: {
            number: function () {
                return $scope.number;
            }
        }
    });
   };
});

Now I want to count number up in the modal and show it outside of the modal. $scope.number affects obviously just the number in the current controller, so how can I set the variable of the outer controller?

Here's my Fiddle .

Your help would be appreciated.

Try _scope = $scope; to hold on reference to outside controller. And inside inner controller, use _scope.number++; Working fiddle:

"http://jsfiddle.net/5xop3wL9/5/"

I would save your data to a service so it can be passed between controllers.

myApp.factory('modalDataService', function () {
    var modalData = {}; 
    return {
        getData: function () {
            return modalData;
        },
        setData: function (newModalData) {
            modalData = newModalData;
        },
        resetData: function () {
            modalData = {};
        }
    };
});

You can then access your data from your controllers by passing in the factory as a dependency and calling functions like this:

modalDataService.getData();
modalDataService.setData(newModalData);
modalDataService.resetData();

You can add a reference to $scope of outer controller and then increment the number using the new reference.

...
$scope.number = 1;
$higherScope = $scope;
...
//Inside submit
$scope.submit = function () {

                    //How to iterate var number in the outer controller?
                    $higherScope.number++;

                    $modalInstance.dismiss('cancel');
                }

Updated Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM