这个Mad-Libs类型的游戏是我的第一个AngularJS应用程序。向用户显示一个框列表(使用ng-repeat
生成),一次一个(感谢ng-show
),在其中输入他们的单词。我希望每个盒子在出现时都会聚焦。我下载了模块focus-if
,它似乎适用于所有项目,但第一项。如何让第一个列表项自动对焦?
以下是相关的HTML div和相关的AngularJS模块代码。 GitHub链接是https://github.com/amcooper/ftfy_speeches。
HTML(请注意输入标记中的focus-if
表达式):
<div id="fillings" ng-show="speechList.panel=='fillingsPanel'">
<h3 class="text-center">{{speechList.selected.name}}</h3>
<h4 class="text-center">{{speechList.selected.author_first_name}} {{speechList.selected.author_surname}}</h4>
<div class="eachFilling" ng-repeat="filling in speechList.selected.fillings track by $index">
<b><i><span class="counter" ng-show="speechList.fillingsCounter==$index">{{$index+1}} of {{speechList.selected.fillings.length}}</span></i></b>
<input type="text" name="filling" id="filling"+{{$index+1}}.toString() class="filling" placeholder="{{filling.pos}}" focus-if="speechList.fillingsCounter==$index" ng-show="speechList.fillingsCounter==$index" ng-model="filling.text" ng-keyup="($event.keyCode==13 && !($last) && speechList.fillingsNext()) || ($event.keyCode==13 && $last && speechList.fillingsSubmit())" />
<button class="btn btn-default btn-sm pull-right" type="submit" ng-show="(speechList.fillingsCounter==$index) && !($last)" ng-click="speechList.fillingsNext()">Next</button>
<button class="btn btn-default btn-sm pull-right" type="submit" ng-show="(speechList.fillingsCounter==$index) && $last" ng-click="speechList.fillingsSubmit()">Finished</button>
</div>
</div> <!-- fillings -->
AngularJS模块:
(function() {
var app = angular.module('speechChoices', ['focus-if','ngSanitize']);
app.controller('SpeechListController', function() {
this.listSubmit = function(clickedIndex) {
//Perhaps validate choice before submitting<br>here? or have default choice.
this.speechIndex = clickedIndex;
this.panel = "fillingsPanel";
this.selected = speeches[this.speechIndex];
console.log("status: " + this.panel + "; index: " + this.speechIndex);
};
this.fillingsSubmit = function() {
this.panel = "resultsPanel";
var j = 0;
this.htmlResult = "";
while (j < this.selected.fillings.length) {
this.htmlResult = this.htmlResult + this.selected.text_snippets[j] + this.selected.fillings[j].text;
j++;
}
this.htmlResult = this.htmlResult + this.selected.text_snippets[this.selected.text_snippets.length-1];
};
this.fillingsNext = function() {
this.fillingsCounter ++;
};
this.initialize = function() {
console.log("Initializing...");
speeches.forEach(function(el,i,ar) {
el.fillings.forEach(function(elf,indexf,arf) {
elf.text="";
});
});
this.speeches = speeches;
this.panel = "listPanel";
this.speechIndex = 0;
this.selected = speeches[this.speechIndex];
this.fillingsCounter = 0;
console.log("status: " + this.panel + "; index: " + this.speechIndex);
};
this.initialize();
});
var speeches = [{
// an array of speech hashes
}];
})();