2014-09-05 172 views
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; 
    } 

}); 
+0

哪裏是你的控制器代碼?我們可以看到它嗎? – alpinescrambler 2014-09-05 03:08:18

+0

Ng在哪裏?如果在你的代碼中。 – PSL 2014-09-05 03:10:16

+0

Opps,我的意思是ng-show。 – 2014-09-05 03:12:01

回答

2

的萬阿英,蔣達清是你總是在變化的局部變量won代替其使用由angularjs的$scopewon財產。的

因此,而不是使用won = true;

$scope.won = true; 

JavaScript中的變量亙古不工作像指針,所以當你說var won = $scope.won = false;你有2個屬性won$scope.wonfalse再後來,當你說won = truewon值改爲true,但$scope.won仍指false即問題所在。因此,在您的控制器中不需要使用局部變量won,因爲它是一個始終處理範圍屬性的原始值。

演示:ProblemSolution