javascript - 无法使用 Angular 中的本地存储将数据保留在范围内

标签 javascript angularjs

我正在使用 fileReader 读取文件并将图像存储在 localStorage 中并将其显示在 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("");
    }
};
}]);

使用工厂将数据推送到服务器:

$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)
    });
};

工厂:

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>

图像已正确上传到服务器,但在页面刷新时,即使使用$localStorage,图像数据也会从$scope清空

注意:ng-file-select ng-file-change 是来自 ng-upload 的指令

最佳答案

发生的情况是,当文件被推送到服务器时,然后刷新页面,因为 Controller 中没有调用方法来重新分配 $scope.profilePic,因此它是空的。

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:您在 $localStorage 中有两个不同的个人资料图片 key ,分别为 $localStorage.profilePicture$localStorage.profilePic。请确保使用右键重新分配。

关于javascript - 无法使用 Angular 中的本地存储将数据保留在范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37598598/

相关文章:

javascript - Rails 中同一 View 中的多个 AJAX 表单

javascript - 在同一页面上多次调用 $(document).ready

angularjs - 防止 gulp 压缩本地机器上的代码

angularjs - UI Bootstrap 和 Angularjs 日期选择器选项卡和直接输入

javascript - Angular - 组件中的函数对于 ng-repeat 无法正常工作

javascript - 包括 href 和 onclick 到 HTML <a> 标签

javascript - Angular.js : ng-repeat OrderBy fails to order values

javascript - 附加非嵌套元素

javascript - Angularjs 错误未知提供者 : $scopeProvider <- $scope <- user

angularjs - 集成 Hive 和 AngularJS?