angularjsangular-ui-modal

Unable to pass API response to uimodal


Below is my code snippet where i'm trying to use uimodal to display the user detail along with additional detail.

I'm failing to bind the response data to uimodal, Kindly help to resolve this.

    $scope.selectedUserData = '';
    $scope.edituser = function (user) {
    usereditService.resp(size.userid, function (response) {
        if (response != false) {
            console.log(response[0]);//Specific user details object from API
            selectedUserData = response[0];
        }
        else {
            console.log('no user found');
        }
    });

    $scope.modalInstance = $uibModal.open({
        animation: false,
        backdrop: 'static',
        templateUrl: '/_views/_editUser.html',
        controller: 'userController',
        size: size,
        resolve: {
            selectedData: function () {
                return $scope.selectedUserData;
            }
        },
        controller: function($scope, selectedData) {
            $scope.editobj = selectedData;
        }
    });

    modalInstance.result.then(function (response) {
        $scope.selected = response;
    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });

};

Solution

  • The data is coming from async response, so can't get that ajax response data as soon as your requested for it.

    You need to follow promise pattern in that case, and return the data in promise chain patter from your resolve's selectedData function.

    //assuming usereditService.resp is returning promise object
    //it it doesn't returning promise object, you need to create it by custom promise using $q
    var userDataPromise = usereditService.resp(size.userid).then(function (response) {
        if (response != false) {
            console.log(response[0]);//Specific user details object from API
            selectedUserData = response[0];
            return selectedUserData;
        }
        else {
            console.log('no user found');
            return 'no user found';
        }
    }, function(error){
        console.log();
        return 'no user found';
    });
    
    $scope.modalInstance = $uibModal.open({
        animation: false,
        backdrop: 'static',
        templateUrl: '/_views/_editUser.html',
        controller: 'userController',
        size: size,
        resolve: {
            selectedData: function () {
                //returning response object here as a promise.
                return userDataPromise;
            }
        },
        controller: function($scope, selectedData) {
            $scope.editobj = selectedData;
        }
    });