kittu
kittu

Reputation: 7018

unable to persist data in scope using localstorage in angular

I am using fileReader to read the file and store the image in localStorage and display it on view.

Controller:

angular.module('App')controller('publsherProfileEditCtrl', ['$rootScope', '$scope', '$stateParams', '$location', '$http', 'Auth', '$state', 'toaster', '$timeout', '$localStorage', 'operationsFactory', 'userManagementFactory', '$q', function ($rootScope, $scope, $stateParams, $location, $http, Auth, $state, toaster, $timeout, $localStorage, operationsFactory, userManagementFactory, $q) {

$scope.profilePicture = {};
var fd;
$scope.onBGSelect = function ($files) {
    var file = $files[0];
    if (!file) {
        return;
    }
    if ((/\.(jpg|jpeg|png)$/i).test(file.name)) {
        fd = new FormData();
        fd.append('content', file);
        var reader = new FileReader();
        reader.onload = (function (theFile) {
            return function (e) {
                $scope.$apply(function () {
                    $localStorage.profilePicture = e.target.result;
                    $scope.profilePicture.content = $localStorage.profilePicture;
                });
            };
        })(file);
        reader.readAsDataURL(file);
    } else {
        toaster.pop('error', "File Extension", "Not allowed.");
        $('input[name="bgimage"]').val("");
    }
};
}]);

pushing data to server using factory:

$scope.publisherProfileEdit = function () {
if ($scope.profilePicture.content) {
    var track = [];
    for (var keys in $scope.profilePicture) {
        fd.append(keys, $scope.profilePicture[keys]);
    }
    track.push(operationsFactory.changeProfilePicture(fd));
    $scope.myPromise = $q.all(track).then(function (result) {
        $localStorage.profile_picture = result[0].data.profile_picture;
        console.log('success upload')
        toaster.pop('success', 'Changed Successfully');
        userManagementFactory.userProfile($localStorage.userId).success(function (response) {
            $localStorage.presentUser = response.result;
            $scope.presentUser = $localStorage.presentUser;
            $localStorage.profilePic = $scope.presentUser.profile_picture;
            $scope.profilePic = $localStorage.profilePic;
        }).error(function (error) {
            console.log('error' + error);
        });
    }, function (error) {
        console.log('error', error)
    });
};

Factory:

angular.module('App').factory('userManagementFactory', function ($http) {
    var BASEURI = 'https://www.crmmgolbale.profile/user/';
    var userProfile = function (data) {
        return $http({
            method: 'GET',
            url: BASEURI + data + '/compact',
            data: data
        });
    };
    return{
        userProfile: userProfile
    };
});

Html view:

<div> 
    <img ng-src="{{profilePic}}">
        <!-- <div ng-if="profilePicture.content">
            <img ng-src="{{profilePicture.content}}"/>
        </div>-->
    <input type="file" name="bgimage" ng-file-select ng-file-change="onBGSelect($files)" ng-model="imageData" accept="" />
</div>

Image is uploaded properly to server but on page refresh the image data is emptied from $scope even after using $localStorage

Note: ng-file-select ng-file-change is directive from ng-upload

Upvotes: 1

Views: 195

Answers (1)

Sajal
Sajal

Reputation: 4401

Whats happening is the when the file is pushed on to the server, then you refresh the page, since there is no calling method in the controller to re-assign the $scope.profilePic, hence it comes empty.

function reloadPage() {
   //You can set the picture again from storage
   $scope.profilePic = $localStorage.profilePicture

   //Or call the factory method again to repopulate it
    userManagementFactory.userProfile($localStorage.userId).success(function (response) {
        $localStorage.presentUser = response.result;
        $scope.presentUser = $localStorage.presentUser;

        //Check if profile pic already exisit
        if($scope.presentUser.profile_picture != null) {
          $localStorage.profilePic = $scope.presentUser.profile_picture;
          $scope.profilePic = $localStorage.profilePic;
        }
         //Set it back from the $localStorage
        else {
          $scope.profilePic = $localStorage.profilePic
        }
   });
}

//Run this method on page-reload as:
reloadPage();

PS: You have two different keys for profile Pic in $localStorage as $localStorage.profilePicture and $localStorage.profilePic.Make sure use the right key for re-assigning.

Upvotes: 1

Related Questions