1

I have a variable called won in my controller that toggles on and off but the ng-show is not dynamically hiding/showing the elements. Why? It seems to work when I initially set won = false/true but not while the application is running.

<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;
  }

});
Andre Tran
  • 11
  • 2

1 Answers1

2

The probelm is you are always changing the local variable won instead of the won property of the $scope which is used by angularjs.

So instead of using won = true;

$scope.won = true;

In javascript the variables doesnot work like pointers, so when you say var won = $scope.won = false; you have 2 properties won and $scope.won referring to false then later when you say won = true the value of won is changed to true but $scope.won still refers to false that is the problem. So there is no need to use a local variable won in your controller, since it is a primitive value always deal with the scope property.

Demo: Problem, Solution

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531