为什么我的Angular数据绑定在视图中无法更新?

3
我正在制作一个基本的JavaScript赛车游戏程序,并尝试使用Angular更新视图中的得分。我已经编写了基本代码来移动玩家并拥有不同的游戏状态。
你可以在这里看到我设置代码的方式:

http://jsfiddle.net/ey8dk22r/1/

由于某种原因,它没有在fiddle中显示,但在我的端上,angular代码将为每个分数显示“0”。如果我将$scope.score_one或two更改为类似“ hello”的东西,则该单词将显示在其位置。目前,我已将{{score_one}}和{{score_two}}设置为player1.score和player2.score。无论最初设置的数字是什么,都将显示出来(0)。当玩家获胜并成功更新玩家的得分时,视图中的得分不会更新。
这是我的js文件的一部分; Player对象和scoreController:
function Player(element_id, name){
  this.el = $(element_id).selector;
  this.position = 1;
  this.name = name;
  this.score = 0;
  this.check = function(){
    if ($(this.el + ' td:last-child').hasClass("active")){
      this.score += 1;
      $(".winner").html("<h2>" + this.name + " wins!</h2>")
      game = false;
      $(".reset").show();
    }
  }
  this.move = function(position){
    $(this.el + ' td').removeClass('active');
    $(this.el + ' td:eq(' + (this.position) + ')').addClass("active");
    this.check();
    this.position += 1;
  }
}

function scoreController($scope){
  $scope.score_one = player1.score;
  $scope.score_two = player2.score;
}

这里是我在html文件中进行数据绑定的地方:

<div class="container" ng-app="" ng-controller="scoreController">

    <h1>A Day at the Races</h1>

    <ol>
        <li ng-model="score_one">Mew: {{ score_one }}</li>
        <li ng-model="score_two">Celebi: {{ score_two }}</li>
    </ol>

所以,我想知道作用域是否有问题,为什么得分没有正确更新。我已经正确地链接了Angular,并尝试使用输入字段进行操作,可以正确地更新视图,但出于某种原因,这不起作用。我查看了$apply并尝试在$apply()中使用$scope.score_one,但我不确定我是否做对了。

如果您有任何想法,请告诉我。谢谢。


2
你是正确的,应该使用$apply来更新模型的值。 - khakiout
1
这里有几个问题。首先,您的jsfiddle存在错误,即使找到您的控制器也无法正常运行。其次,我没有看到您定义angular应用程序的位置:angular.module(“App”,[])在哪里?在我们谈论“第三个”问题之前,您能先解决这个问题吗? - New Dev
1个回答

3
我认为你的问题更多地与如何设置你的代码有关,而不是具体的语法问题。一般来说,jQuery和Angular并不太兼容。根据Angular文档:
“Angular是否使用jQuery库?” 答:如果在应用程序启动时存在jQuery,则Angular可以使用jQuery。如果jQuery不在脚本路径中,则Angular会退回到我们称之为jQLite的jQuery子集的自己实现。 Angular 1.3只支持jQuery 2.1或更高版本。 jQuery 1.7及以上版本可能与Angular正确配合使用,但我们不能保证。
我看到你正在使用jQuery 1.11和Angular 1.2.15,因此你属于“可能”正常工作的类别。如果我是你,我会选择其中一个工具并使用它。
最后,如果你要使用Angular,你需要先实例化你的模块,然后定义你的控制器。下面这个示例可以工作:
var myAppModule = angular.module('myApp', []);
myAppModule.controller('scoreController', '$scope', function($scope) {
    $scope.score_one = player1.score;
    $scope.score_two = player2.score;
}

你需要以类似的方式构建增加分数的方法。简而言之,我会在Angular中保留所有内容,甚至不考虑jQuery。在这样的应用程序中做双向绑定,Angular非常棒,因此我认为这是最好的选择。祝好运。


谢谢。我没有意识到同时使用Angular和jQuery会出现问题。我将只使用Angular再试一次。 - Justin Wagner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接