将变量设置为$ scope值

时间:2016-08-24 21:30:45

标签: javascript angularjs

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

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

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

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>

1 个答案:

答案 0 :(得分:0)

尝试移动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。