【问题标题】:ngStorage not working properly when redirect using window.location使用 window.location 重定向时,ngStorage 无法正常工作
【发布时间】:2015-01-01 18:17:14
【问题描述】:

我正在尝试使用 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 行,它可以正常工作。

我是不是按错误的顺序做某事?

【问题讨论】:

    标签: window.location angular-local-storage


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      $localStorage.$apply();
      

      帮我搞定了

      感谢github issue comment

      【讨论】:

        【解决方案3】:
        var setLocalStorage = function (token, uname)
        {
        $localStorage.token = token;
        $localStorage.name = uname;
        
        }
        $timeout(setLocalStorage(token, userForm.uname), 500);
        

        使用的模块:ngStorage

        $localStorage.apply(); //在本地存储中添加值后使用这个。无需超时。

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

            猜你喜欢
            • 2013-11-16
            • 1970-01-01
            • 2017-09-23
            • 2015-08-09
            • 2014-07-01
            • 2015-12-21
            • 2017-03-04
            相关资源
            最近更新 更多