所以我正處於與Angular JS交互遊戲的開始階段。過去兩天,我一直在爲如何去屏幕上輸入錯誤猜測而不是記錄輸入的每個猜測而困惑不已。我的目標是最終有一個最大錯誤的猜測量爲10,然後用戶輸了。我只是不知道該怎麼做。 Angular是新手,但無法用普通的JS來搞清楚。任何幫助或暗示將不勝感激。Angular JS陣列解析
app.controller('MainController', ['$scope', function($scope) {
var answerArray = ["linux","macintosh","windows"];
var answer = answerArray[Math.floor(Math.random() * answerArray.length)];
$scope.answer = answer;
$scope.userGuesses = [];
$scope.wrongGuesses = [];
$scope.guessTracker = 0;
$scope.guessCheck = function(){
if($scope.userGuesses.indexOf($scope.guess) === -1){
$scope.userGuesses.push($scope.guess);
}
$scope.guess = "";
};
$scope.letterDisplay = function(){
var chars = $scope.answer.split("");
_.each(chars, function(val, index){
if($scope.userGuesses.indexOf(val) === -1){
chars[index] = "_";
}
});
return chars;
};
}]);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://jashkenas.github.io/underscore/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="hangMan">
<div class="container" ng-controller="MainController">
<div class="row text-center">
<h1>Save Bernie</h1>
</div>
<div class="row text-center">
<div class="col-md-12">
<div id="messageDisplay">
<span ng-repeat="char in letterDisplay() track by $index">
{{char}}
</span>
</div>
</div>
</div>
<!-- Drawing -->
<div id="mainContent" class="row rowspacing">
<div class="col-md-6">
<div id="drawingWrapper">
<div id="pole"></div>
<div id="poleExtension"></div>
<div id="rope"></div>
<div id="torso"></div>
<div id="head"></div>
<div id="leftArm"></div>
<div id="rightArm"></div>
<div id="leftLeg"></div>
<div id="rightLeg"></div>
<div id="hillary"></div>
</div>
</div>
<!-- Controls -->
<div class="col-md-6 text-center">
<div id="userSubmit">
<form ng-submit="guessCheck()">
<input type="text" name="guess" ng-model="guess" required><button>Guess</button>
</form>
<div id="guessDisplay" ng-repeat="character in userGuesses track by $index">
{{character}}
</div>
</div>
</div>
</div>
</div>
<script src='/js/bootstrap.min.js'></script>
<script>var app = angular.module("hangMan", []);</script>
<script src='/js/MainController.js'></script>
沒問題,非常感謝答覆。 –
理想情況下,我不想使用underscore.js關於我可以實現什麼而不是_.each函數的任何快速建議? –