0

I'm trying to build the User Interface of a game, and AngularJS seems to be perfect for that matter. All my game is inside the global variable ig. ig looks like this :

ig = { money: 100, lives: 3, ... };

I'd like to add ig.money and ig.live to the scope of the controller, so it automatically updates the UI when the variable change within the game.

I tried :

$scope.$watch('ig.money', function() { $scope.money = ig.money; });

but it doesn't work. It says that ig is null. Can someone point me in the right direction? Thank you

0

3 Answers 3

5

or that would be more angular way:

app.value('myGame',ig)
app.controller('AppController',[
    '$scope',
    '$window',
    function($scope,myGame) {
      $scope.ig = myGame;
    }
]);

or you could put your game in a constant or provider or factory or service

module

it's up to you choice the way that better fits your needs

Sign up to request clarification or add additional context in comments.

Comments

2

Its not clear where and How you have defined your global variable.

Assuming that you have defined your variable as

<script type="text/javascript">
    var ig = { money: 100, lives: 3, ... };
</script>

To Access these variables in Angular controller you have to inject $window into your controller to access your window-bound variables.

app.controller('AppController',[
    '$scope',
    '$window',
    function($scope, $window) {
      $scope.ig = $window.ig;
    }
]);

2 Comments

It doesn't work on my game, but work on a simple test I made : jsfiddle.net/X374y . In my game, the template is updated only when I call the test() function. I'll investigate this, but your answer is valid. Thank you!
I managed to reproduced what is happening on my game : jsfiddle.net/L5AB9 . This time the money is not updated by any angular method (like my game). And I have to press the TEST button for the template to be updated. Any idea?
1

A clean way is to put all your game data in an Angular Service which is a singleton. Any changes to the data can then be broadcasted to controllers that can act on that event. Via dependency injection you can make your service with the game data easily accessible to all controllers. There is a great blogpost that gives a straightforward example on how to do this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.