使用 window.location 重定向时 ngStorage 无法正常工作

ngStorage not working properly when redirect using window.location

我正在尝试使用 ngStorage 模块在设置 $storage var 后进行重定向。这不起作用,我无法找出原因。

我的代码如下:

  <head>
    <script data-require="angular.js@1.1.5" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>

    <script>
        angular.module('app', [
          'ngStorage'
        ]).

        controller('Ctrl', function (
          $scope,
          $localStorage
        ) {
            $scope.$storage = $localStorage.$default({                
                array: []
            });
            $scope.Redirect1 = function () {
                $scope.$storage.array = ['pineapple', 'pear', 'peach'];
                window.location.href = 'http://localhost:61267/Page1.aspx?q=fruitsp';
            };
            $scope.Redirect2 = function () {                
                $scope.$storage.array = ['blackberry', 'banana', 'blueberry'];
                window.location.href = 'http://localhost:61267/Page1.aspx?q=fruitsb';
            };
        });
    </script>
  </head>

  <body ng-controller="Ctrl">    
    {{$storage|json}}
    <br/>
    <button ng-click="Redirect1();">Change Array</button><br/>
    <button ng-click="Redirect2();">Change Array2</button>
  </body>

</html>

如果我删除 window.location 行,它会正常工作。

我是不是顺序错了?

此问题已由@claireablani 回答。 页面重新加载似乎发生在对 localStorage 进行修改之前。

您可以使用@raynode 的 ngStorage 库的分支(Github here,在 bower 上不可用),它添加了一个 $save() 方法来确保修改已被应用。

$localStorage.$apply();

对我有用

多亏了这个github issue comment

var setLocalStorage = function (token, uname)
{
$localStorage.token = token;
$localStorage.name = uname;

}
$timeout(setLocalStorage(token, userForm.uname), 500);

Module Used : ngStorage

$localStorage.apply(); //Just after adding values in localstorage use this. No timeout required.

我也 运行 关注这个问题。我试图在 service 中更新 localStorage,但它似乎没有用。至少不在承诺之内。在那里尝试了 $localStorage.$apply() 和 $timeout,但没有用。我必须将代码移入我的 控制器 才能完成这项工作。

$scope.$localStorage.myVar = 'test';
$scope.$localStorage.$apply();
$state.go('app.home');