Angular localstorage数组未显示在HTML

时间:2018-12-13 14:13:07

标签: javascript angularjs node.js

我将数组中的前5个高分保存在localstorage中,但是当我尝试在HTML中显示它时,它不会出现。

我正在使用GameService.getScores()函数从本地存储中获取数组,并引用$ scope.scores数组以HTML填充列表。

我是Angular a Node.js的菜鸟,我不知道自己在做什么错。有什么想法吗?

这是我的控制器文件和HTML文件:

var app = angular.module('app', []);

app.controller('GameController', function($scope, GameService) 
{
  var highScores = GameService.getScores();
  
  $scope.scores = highScores;

  $scope.submitEntry = function() 
  {
    if (typeof $scope.name === 'undefined' || typeof $scope.word === 'undefined') 
    {
			return;
    }
    
    var entry = {
      name: $scope.name,
			word: $scope.word
    };
    
    var score = GameService.submitEntry(entry);

    var userScore = {
      name: entry.name,
			points: score
		};
   
    if (score > 0)
    {
      if ($scope.scores.length < 5)
      {
        $scope.scores.push(userScore);

        localStorage.setItem("highScores", JSON.stringify($scope.scores));

        return;
      }
      else
      {
        for (let i = 0; i < $scope.scores.length; i++) 
        {
          if (score > $scope.scores[i].points)
          {
            $scope.scores.splice(i, 1, userScore);

            localStorage.setItem("highScores", JSON.stringify($scope.scores));

            return;
          }
        }
      }
    }
  };
});

app.service('GameService', function($http) 
{
  this.getScores = function() 
  {
    var hs = [];
    
    if(localStorage.getItem('highScores') != null)
    {
      hs = localStorage.getItem('highScores');

      if (hs) 
      {
        hs = JSON.parse(hs);
      } 
    }
    
    return hs;
	};
  this.submitEntry = function(entry) 
  {
    var score = 0;
    
    var revStr = "";
    var str = entry.word;
    var i = str.length;

    for(var j=i; j>=0; j--)
    {
      revStr = revStr + str.charAt(j);
    }
    if(str == revStr)
    {
      alert(str + " is Palindrome");

      score = str.length;
    }
    else
    {
      alert(str + " is not a Palindrome");
    }

    return score;
	};
});
<!DOCTYPE html>
<html ng-app="app">
  
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
  </head>
    
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="ng/app.js"></script>

  <body >
    <div ng-controller="GameController" class='container'>
      <h1>Palindrome Game</h1>
		  <h2>Submit a new word!</h2>

      <form role='form'>
        <div class='form-group'>
          <input ng-model="name" class='form-control' placeholder="Your name">
          <input ng-model="word" class='form-control' placeholder="Word">
          <button ng-click='submitEntry()' class='btn btn-default'>Submit word</button>
        </div>
      </form>
  
      <h2>Top Scores</h2>
      <ul class='list-group'>
			  <li ng-repeat="score in scores | orderBy:'-points'" class='list-group-item'>
				  <strong>{{score.name}}</strong> {{score.points}} points
			  </li>
		  </ul-->
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您的代码实际上正在工作:https://jsfiddle.net/BPagoaga/8jcuqds7/1/

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
  </head>

  <body >
    <div ng-controller="GameController" class='container'>
      <h1>Palindrome Game</h1>
          <h2>Submit a new word!</h2>

      <form role='form'>
        <div class='form-group'>
          <input ng-model="name" class='form-control' placeholder="Your name">
          <input ng-model="word" class='form-control' placeholder="Word">
          <button ng-click='submitEntry()' class='btn btn-default'>Submit word</button>
        </div>
      </form>

      <h2>Top Scores</h2>
      <ul class='list-group'>
              <li ng-repeat="score in scores | orderBy:'-points'" class='list-group-item'>
                  <strong>{{score.name}}</strong> {{score.points}} points
              </li>
          </ul>
    </div>
  </body>
</html>

var app = angular.module('app', []);

app.controller('GameController', function($scope, GameService) 
{
  var highScores = GameService.getScores();

  $scope.scores = highScores;

  $scope.submitEntry = function() 
  {
    if (typeof $scope.name === 'undefined' || typeof $scope.word === 'undefined') 
    {
            return;
    }

    var entry = {
      name: $scope.name,
            word: $scope.word
    };

    var score = GameService.submitEntry(entry);

    var userScore = {
      name: entry.name,
            points: score
        };

    if (score > 0)
    {
      if ($scope.scores.length < 5)
      {
        $scope.scores.push(userScore);

        localStorage.setItem("highScores", JSON.stringify($scope.scores));

        return;
      }
      else
      {
        for (let i = 0; i < $scope.scores.length; i++) 
        {
          if (score > $scope.scores[i].points)
          {
            $scope.scores.splice(i, 1, userScore);

            localStorage.setItem("highScores", JSON.stringify($scope.scores));

            return;
          }
        }
      }
    }
  };
});

app.service('GameService', function($http) 
{
  this.getScores = function() 
  {
    var hs = [];

    if(localStorage.getItem('highScores') != null)
    {
      hs = localStorage.getItem('highScores');

      if (hs) 
      {
        hs = JSON.parse(hs);
      } 
    }

    return hs;
    };
  this.submitEntry = function(entry) 
  {
    var score = 0;

    var revStr = "";
    var str = entry.word;
    var i = str.length;

    for(var j=i; j>=0; j--)
    {
      revStr = revStr + str.charAt(j);
    }
    if(str == revStr)
    {
      alert(str + " is Palindrome");

      score = str.length;
    }
    else
    {
      alert(str + " is not a Palindrome");
    }

    return score;
    };
});

我删除了此内容:

<script src="ng/app.js"></script>`

但我不确定是否有问题。

取决于测试代码的方式(stackoverflow上的代码段,jsfiddle)以及使用哪种浏览器,相同来源策略可能会遇到一些问题。

在Chrome上,我必须取消选中“阻止第三方Cookie”才能使其正常运行。在Firefox上,它仍然无法正常工作,该操作被阻止,因为浏览器认为它是不安全的。

我建议您在计算机上而不是在jsFiddle之类的在线沙箱中尝试代码。