2016-02-03 48 views
1

我一直在嘗試一段時間來獲取控制器的範圍來識別工廠變量。Angular - 無法看到工廠變量

這裏是我的index.html

<div ng-controller='scoresController'> 
    <div id='game-info' ng-hide='!playing'> 
     <p id='level'>Level: {{ level }} 
      <span id='score'>Score: {{ score }}</span> 
      <span id='high-score'>High Score: {{ highScore() }}</span> 
      <span id='coins'>Coins: <span class='coins-badge'> {{ coins }} </span></span> 
     </p> 
    </div> 
</div> 

這裏是我廠

angular.module('my-app') 
    .factory('Game', function() { 
     return { 
      level: 1, 
      score: 0, 
      playing: false, 
      coins: localStorage['snakeCoins'] 
     }; 
    }); 

這裏是我的控制器與$watch功能

angular.module('my-app') 
.controller('scoresController', ['$scope', 'Game', function($scope, Game) { 

    $scope.score = Game.score; 
    $scope.level = Game.level; 
    $scope.playing = false; 
    //$scope.coins = localStorage['snakeCoins']; 

    // Why aren't the changes being registered? 
    $scope.$watch(function() { 
     return Game.playing; 
     }, function(newVal, oldVal) { 
     $scope.playing = newVal; 
    }, true); 

    $scope.$watch(function() { 
     return Game.score; 
     }, function(newScore, oldScore) { 
     if (newScore > oldScore) { 
      console.log(newScore); 
      $scope.score = newScore; 
     } 
    }); 

    $scope.$watch(function() { 
     return Game.level; 
     }, function(newLevel, oldLevel) { 
     if (newLevel > oldLevel) { 
      $scope.level = newLevel; 
     } 
    }); 

但是,我知道,工廠變量變化因爲我將結果記錄到控制檯

$scope.incrementScore = function() { 
     if (!playing) { 
      if (apple['x'] == snake[0].x && apple['y'] == snake[0].y) { 
       Game.score++; 
       console.log(Game.score);  //Logging here 
       $scope.incrementLevel(); 
       $scope.generateApples(); 
       $scope.drawApple(apple['x'], apple['y']); 
       snake.push({ x: snake.length, y: 0 }); 

      } 
     } 
    } 

它不能是包含文件的順序。

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script> 
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'></script> 
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js'></script> 
<script src='scripts/data.js'></script> 
<script src='scripts/app.js'></script> 
<script src='scripts/services/game.js'></script> 
<script src='scripts/controllers/navController.js'></script> 
<script src='scripts/controllers/achievementsController.js'></script> 
<script src='scripts/controllers/scoresController.js'></script> 
<script src='scripts/controllers/gamesController.js'></script> 

不知道,爲什麼我不能$watch注意到的變化。任何理論?

+0

你的問題是回答? –

+0

是的。感謝您的幫助 –

回答

2

您應該使用$rootScope.$watch

1

您可以通過它分配給Game的範圍,即

.controller('scoresController', function($scope, Game) { 
    $scope.game = Game; 

和模板簡化這個...

<span id="score">Score: {{ game.score }}</span> 

這樣,你不需要設置任何手動觀察者。