如何在ng-repeat中使用localStorage值过滤器

时间:2017-09-02 17:09:58

标签: javascript angularjs local-storage

我在用户点击投票选择时设置了一个值。它的工作。

.then(function(response) { 
  localStorage.setItem('isClicked', 'Yes');
  var i = +localStorage.key("nid");
  var nidId = 'nid' + localStorage.length;
  localStorage.setItem(nidId, vm.nid);
  vm.clickedBefore = true;
})

这是我的HTML范围:

<div class="card myfunc" ng-repeat="myfunc in myfuncPage.myfuncs" id="{{myfunc.nid}}"  >

  <div class="item item-text-wrap">
    <h2 class="item-icon-left"><i class="icon ion-ios-analytics"></i>
      {{myfunc.title}}</h2>
    </div>
    <div class="item item-text-wrap" ng-show="localstorage">
      <img ng-src="{{myfunc.field_image.und[0].imgPath}}"/>
      <p class="custom-class" ng-bind-html='myfunc.body.und[0].value'>
      </p>
      <ul ng-repeat="vote in myfunc.advmyfunc_choice">
        <li ng-repeat="voteselect in vote">
          <div class="row">
            <button class="col button button-outline button-dark" ng-click="myfuncPage.sendNid(myfunc);myfuncPage.sendVote(voteselect);showVoted = ! showVoted" >{{voteselect.choice}}</button>
            <div class="voted-screen" ng-show="showVoted">
              <h3>Thanks.</h3>
            </div>      
          </div>
        </li>
      </ul>

    </div>

  </div>

基本上,我需要通过localStorage记住div,当页面刷新时,隐藏选择div。

ng-show="showVoted"处理点击,但我需要刷新。

最好的方法是什么?感谢。

1 个答案:

答案 0 :(得分:0)

我不确定您使用的是哪个本地存储模块,因此我不具体,但我会编写工厂来处理您需要的值的检索和存储

(function () {
  var voteFactory = function (localStorage) {
        return {
            getVote: function (key) {
               var isVoted = false;  

               // get local storage item, set voted etc
               var voted = localStorage.getItem(key);
               if(voted) {
                  isVoted = voted;
               }
               return isVoted;

            },
            setVote: function(key, value) {
               localStorage.setItem(key,value);
            }          
         };
       };
      app.factory('voteFactory', ['localStorage', voteFactory]);
 })();    

然后在用于显示或隐藏的范围控制器/指令中,您将拥有一个函数:

$scope.showVoted = function(key) {
  return voteFactory.getVote(key);
}

然后ng-show =&#34; showVoted(theidentifieryouwantouse)&#34;

值得一提的是我会使用ng-if代替ng-show。为了提高效率,您可以将投票存储为数组而不是单个值,并检查是否已检索到所有值,如果没有,则从本地存储获取。然后,您的函数将询问检索到的数组,而不是重复调用本地存储。我也建议在工厂使用承诺,因为从本地存储中检索可能会延迟,导致一些奇怪的事情。

希望这与您所寻找的一致。如果需要,我可以详细说明。

相关问题