javascript - AngularJS Using $timeout giving undefined error -
im trying make 1 of these memorization games, u need flip 2 cards on , try match images on other side otherwise both turn over.
my code working fine, except need add delay/pause before 2 cards flipped on if no match made. i'm trying use $timeout
, i'm getting error: typeerror: cannot set property 'isflipped' of undefined
html
<body ng-controller="mainctrl main"> <figure ng-class="{true: 'flipped', false: 'not-flipped'}[card.isflipped]" class="card" ng-repeat="card in cards" ng-click="flipcard(card.id, card.pair)"> <img ng-src="img/cardback1.png" class="back"></img> <img ng-src="{{card.img}}" class="front"></img> </figure> </body>
myctrl
angular.module('cardapp').controller('mainctrl', ['$scope', '$timeout', function($scope, $timeout) { $scope.cards = [ { img: 'img/chantal1.jpg', id: 1, isflipped: false, pair: 1, matched: false, }, { img: 'img/chantal1.jpg', id: 2, isflipped: false, pair: 1, matched: false, }, { img: 'img/chantal2.jpg', id: 3, isflipped: false, pair: 2, matched: false, }, { img: 'img/chantal2.jpg', id: 4, isflipped: false, pair: 2, matched: false, }, { img: 'img/chantal3.jpg', id: 5, isflipped: false, pair: 3, matched: false, }, { img: 'img/chantal3.jpg', id: 6, isflipped: false, pair: 3, matched: false, }, ]; $scope.unflipcards = function(k, i) { $scope.cards[k].isflipped = false; $scope.cards[i].isflipped = false; }; $scope.flipcard = function(id, pair) { var cards = $scope.cards; for(var = 0, j = cards.length; < j; i++) { // find card id in cards not matched if(cards[i].id == id && cards[i].matched == false) { // flip card cards[i].isflipped = !cards[i].isflipped; // check if other cards flipped for(var k = 0, j; k < j; k++) { // if find card flipped , not yet matched if(cards[k].isflipped == true && cards[k].matched == false && cards[k].id != id) { // check if card pair current card if(cards[k].pair == pair) { // set matched true cards[k].matched = true; cards[i].matched = true; } else { $timeout(function(){$scope.unflipcards(k, i)}, 1000); // undefined error //$scope.unflipcards(k, i); // works } } } } } }; }]);
i try reproduct in jsfiddle now
by end of cycle, k
, i
1 above last cards index. both $scope.cards[k]
, $scope.cards[i]
don't exist , therefor undefined.
you this:
$scope.unflipcardstimeout = function(k, i) { $timeout(function(){$scope.unflipcards(k, i)}, 1000); };
and in loop replace:
$timeout(function(){$scope.unflipcards(k, i)}, 1000);
with:
$scope.unflipcardstimeout(k, i);
Comments
Post a Comment