简体   繁体   中英

Pass Angular modal data to main controller

I have a controller inside which i am using a modal. Please check this

'use strict'
var DataMod = angular.module('Data', ["angularGrid", 'ui.bootstrap.contextMenu', 'ui.bootstrap']);
DataMod.controller('DataController', ['$scope', '$compile', '$uibModal', '$log','$rootScope', '$http', function ($scope, $compile, $uibModal,$log, $rootScope, $http, ngUtilityService) {


$scope.adduser = function () {


    var modalInstance = $uibModal.open({
        templateUrl: 'myModalContent.html',
        controller: ModalInstanceCtrl
    });

};

//use data value here. 



var ModalInstanceCtrl = function ($scope, $uibModalInstance) {

    var data = "analog";

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
};


}

]);

As you can see, the user clicks on 'Add user' tab. the add user function gets executed and a modal pops up. There are several internal processing which i have done.

At the end, i want to transfer one variable 'data' back to the main controller. Can someone please let me a simple example of how to transfer data from modal to controller.

I have seen several examples and understood resolve will help me achieve it. But i am confused on it totally...

If you define ModalInstanceCtrl inside the scope of DataController you should be able to share a variable using closure.

Ex:

var data = {
   name:"Foo"
}
$scope.data = data;
var ModalInstanceCtrl = function ($scope, $uibModalInstance) {
    //accessing data from the controller using closure.
    data.name = "analog";

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
};

$scope.adduser = function () {


    var modalInstance = $uibModal.open({
        templateUrl: 'myModalContent.html',
        controller: ModalInstanceCtrl
    });

};
$scope.processData = function(){
      //do something with data 
};
$scope.$watch('data', function (old, new){
    //if data changed do somthing
});

//if you use data here it will have no value yet.
//use data value here. 

You can also use a Service and let both controllers access it. The modal will change the state of a variable inside this service and the DataController will get it from the Service.

An example of service would be:

DataMod.Service('Data', function () {

    var data = {
        FirstName: ''
    };

    return {
        getFirstName: function () {
            return data.FirstName;
        },
        setFirstName: function (firstName) {
            data.FirstName = firstName;
        }
    };
 });

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