gpt4 book ai didi

javascript - 将变量设置为 $scope 值

转载 作者:行者123 更新时间:2023-11-28 05:38:36 24 4
gpt4 key购买 nike

编辑:根据之前的答案,JS 已被修改为运行 http.get 中的所有代码。我还添加了 HTML。

当前页面可以查看:http://www.kamac.co.uk/wordplay3/#/gamecontrol

我有一个 AngularJS 应用程序, Controller 中包含以下代码:

var vm = this;

$http.get('data/data.json').success(function(data) {
$scope.entries = data;
var rand = Math.floor(Math.random()*$scope.entries.length);

$scope.selectedWord = $scope.entries[rand].word;
$scope.selectedDefinition = $scope.entries[rand].definition;

vm.topsecret = "TopSecret";
vm.letter = [];

vm.checkLetter = function(index){
if(vm.topsecret[index] === vm.letter[index]){
vm.result = "letter was correct"
} else {
vm.letter[index] = "";
vm.result = "nope";
}
}

代码的两部分都按预期执行。 $http.get 函数读取 JSON 文件并将 $scope.selectedWord 设置为随机选择的单词。

第二部分为 vm.topsecret 中保存的单词中的每个字母创建多个输入框。

我的问题是,只有当 vm.topsecret 被硬编码时,这才有效。如何使 vm.letter 等于 $scope.selectedWord ?

我尝试了显而易见的方法:vm.topsecret = $scope.selectedWord,但这会导致空值。

HTML

<section class="spellbound container-fluid">
<div class="jumbotron">
<h1>SpellBound</h2>
<p>Below you will see a definition of one of the words in the dictionary. Enter a correct letter and the square turns green - enter a wrong letter and it turns red.</p>
</div>

<div class="panel panel-info">
<div class="panel-heading">How do you spell the word that means</div>
<div class="panel-body">{{selectedDefinition}}</div>
</div>

<p>Answer: {{selectedWord}}</p>

<p>VM: <span>{{vm.topsecret}}</span>

<div ng-controller="GamecontrolController as vm">
<input type="text" ng-model="vm.letter[$index]" ng-repeat="letter in vm.topsecret track by $index" ng-change="vm.checkLetter($index)"/>
<p><span>{{vm.result}}</span></p>
</div>
<div>
<a ng-click="reloadPage()" class="btn btn-info btn-lg" role="button">Play Again</a>
<a href="#/home" class="btn btn-info btn-lg" role="button">Back To Menu</a>
</div>

最佳答案

尝试像下面这样移动 vm.topsecret:

var vm = this;
$http.get('data/data.json').success(function(data) {
$scope.entries = data;
var rand = Math.floor(Math.random()*$scope.entries.length);

$scope.selectedWord = $scope.entries[rand].word;
$scope.selectedDefinition = $scope.entries[rand].definition;
vm.topsecret = $scope.selectedWord;
});



vm.letter = [];

vm.checkLetter = function(index){
if(vm.topsecret[index] === vm.letter[index]){
vm.result = "letter was correct"
} else {
vm.letter[index] = "";
vm.result = "nope";
}
}

这只是一个猜测,因为我看不到您的 HTML 以及您如何使用 vm.topsecret。

关于javascript - 将变量设置为 $scope 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39133337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com