1

我有一个won在我的控制器中调用的变量,它可以打开和关闭,但 ng-show 不是动态隐藏/显示元素。为什么?它似乎在我最初设置时有效,won = false/true但在应用程序运行时无效。

<div class='container' ng-controller='CardsCtrl'>
  <div class='win' ng-show='won'>
    <img ng-src='images/win.gif'>
  </div>
  <div ng-show='!won' ng-repeat='card in cards' ng-click='card.flipped || changeState(card)'
      ng-class="{'card' : !card.flipped, 'card flipped': card.flipped}">
    <img ng-src='{{card.back}}' class='back side'>
    <div class='face side'>
      <img ng-src='{{card.logo}}' class='logo'>
    </div>
  </div>

</div>
var memoryApp = angular.module('memoryApp', []);

memoryApp.controller('CardsCtrl', function ($scope, $timeout){
  var won = $scope.won = false;
  var cards = $scope.cards = [];
  var current_cards = [];
  var checkingCards = $scope.checkingCards = false;


  var logos = _.shuffle([0,0,1,1,2,2,3,3,4,4,5,5]);
  for (var i = 0; i < 12; i++){
    new_card = new Card(logos[i]);
    // $interval(new_card.oscillate, 2000);
    cards.push(new_card);

  }
  cards = _.shuffle(cards);


  $scope.changeState = function (card) {
    won = !won;
    console.log(won);
    // if (checkingCards){
    //   return;
    // }
    // card.flip();
    // current_cards.push(card);
    // if (current_cards.length === 2){
    //   checkingCards = true;
    //   $timeout(compareCards, 1500);
    // }
  }

  function compareCards(){
      if (!current_cards[0].compare(current_cards[1])){
        current_cards[0].flip();
        current_cards[1].flip();
      }

      if (checkWon()){
        won = true;
      }
      current_cards = [];
      checkingCards = false;
      console.log(won);
  }

  function checkWon(){
    for (var i = 0; i < cards.length; i++){
      if (cards[i].flipped === false){
        return false;
      }
    }
    return true;
  }

});
4

1 回答 1

2

问题是您总是在更改局部变量won而不是angularjs 使用的won属性$scope

所以而不是使用won = true;

$scope.won = true;

在 javascript 中,变量不像指针那样工作,所以当你说var won = $scope.won = false;你有 2 个属性won并稍后$scope.won引用时,当你说值更改为但仍然指的是问题时。所以没有必要在你的控制器中使用局部变量,因为它是一个原始值,总是处理范围属性。falsewon = truewontrue$scope.wonfalsewon

演示:问题解决方案

于 2014-09-05T03:12:22.293 回答