0

I am totally new to AngularJs but I have managed to learn the basics of the framework. However, I have recently encountered an exotic behavior from AngularJs ,which is known for being dynamic.

Here is the issue:

Index.html

<div ng-controller="userClick as clk">
 <div id="square1">{{ clk.board[0] }}</div>
</div>

app.js

app.controller('userClick', function($timeout) {
   this.board = ['', '', '', '', '', '', '', '', ''];

$timeout(reset, 1000);
function reset (){
 this.board = ['', '', '', '', '', '', '', '', ''];
 console.log(this.board); //returns ^^ (empty array)
}

It is expected that when the user clicks on one of the squares on the page, that a function is executed and everything goes well. But when I try to use the $timeout function to delay the response for a second, the array this.board gets reset successfully to an empty one but the div there with the id square1 doesn't gets empty back again.

It seems that something causes Angular to be static at this point that I don't get.

Note: It is a Tic Tac Toe game.

4
  • 2
    this inside reset() function isn't same this as outside function. Has nothing to do with angular , is a javascript scope issue Commented May 1, 2016 at 12:17
  • So how to change the board array with the correct scope ?? Commented May 1, 2016 at 12:22
  • in controller store reference to this in variable and use that variable inside function instead of this. See github.com/johnpapa/angular-styleguide/blob/master/a1/… Commented May 1, 2016 at 12:23
  • @charlietfl Thanks a lot it finally worked !! Commented May 1, 2016 at 12:32

1 Answer 1

1

You could declare the reset function as a controller function and use that instead.

app.controller('userClick', ['$timeout', function($timeout) {
    var ctrl = this;
    ctrl.board = ['', '', '', '', '', '', '', '', ''];

    ctrl.reset = function() {
       ctrl.board = ['', '', '', '', '', '', '', '', ''];
       console.log(ctrl.board); 
    };
    $timeout(ctrl.reset, 1000);

    // Rest of your controller logic
}]);
Sign up to request clarification or add additional context in comments.

4 Comments

shouldn't set ctrl as global variable
@charlietfl why? I am sure I am not going to create another controller or a variable with the same name
@YEAMA because it is a terrible practice that can lead to all sorts of hard to find bugs. Should always declare variables using var
@sebastianForsberg What if I wanted to change this ctrl.board array from outside the controller ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.