2015-04-04 69 views
0

我正在嘗試做一個基本函數,它每秒將變量'wood'加1。

在JavaScript中,一個簡單的

setInterval(function(){ 
    wood++; 
}, 1000); 

會做的伎倆。

在轉角,我已經被證明

app.controller('RandomCtrl', function($interval){ 
    this.wood = 0; 
    $interval(function(){ 
     this.wood++; 
    }, 1000); 
}); 

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<script> 
 
    var app = angular.module('app', []); 
 
    app.controller('RandomCtrl', function($interval){ 
 
     this.wood = 0; 
 
     $interval(function(){ 
 
      this.wood++; 
 
      document.getElementById('p').innerHTML = this.wood; 
 
     }, 1000); 
 
    }); 
 
</script> 
 
<div ng-app='app' ng-controller='RandomCtrl as rand'> 
 
    Wood: {{ rand.wood }} 
 
    <br><br>Wood's value straight from the $interval:<p id='p'></p> 
 
    So, the interval is fine, but the variable is undefined inside it, which is the whole point of me using this interval. 
 
    <br><br>Also, I want this.wood to hold the value, nothing else. 
 
</div>

然而,上述因某種原因不能正常工作的代碼。

它把this.wood + 1爲 '男' 和this.wood爲 '未定義'

這裏的片段:

+3

在您的角度示例中,此上下文有所不同。使用var self = this;在外部函數中,並在$ interval中使用self.wood ++。 PS這不是角度特定的JavaScript的基礎知識 – 2015-04-04 22:11:33

+0

哇!謝謝!棒極了! – Tobsta 2015-04-05 00:15:22

回答

2

http://ryanmorr.com/understanding-scope-and-context-in-javascript/

上下文最常被確定一個函數是如何被調用的。當 函數被調用作爲對象的方法,this被設定爲方法稱爲上

當被調用時作爲未結合的函數的對象 ,this將默認爲全球 上下文或窗口對象在瀏覽器。但是,如果函數 以嚴格模式執行,則上下文將默認爲未定義。

只需使用angulars $範圍或在外部函數範圍內聲明的變量:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<script> 
 
    var app = angular.module('app', []); 
 
    app.controller('RandomCtrl', function($interval, $scope){ 
 
     var self = this; 
 
     self.wood = 0; 
 
     $scope.wood = 0; 
 
     $interval(function(){ 
 
      $scope.wood++; 
 
      self.wood++; 
 
     }, 1000); 
 
    }); 
 
</script> 
 
<div ng-app='app' ng-controller='RandomCtrl as rand'> 
 
    Wood: {{ wood }} {{ rand.wood }} 
 
    <br><br>Wood's value straight from the $interval:<p id='p'></p> 
 
    So, the interval is fine, but the variable is undefined inside it, which is the whole point of me using this interval. 
 
    <br><br>Also, I want this.wood to hold the value, nothing else. 
 
</div>

0

這裏的問題是,您要訪問一個新的上下文的範圍,「這個」不再指向你的角度控制器。

另外,Angular允許通過控制器的範圍訪問變量。如果您想在模板中使用可變木材,則必須將其分配給作用域對象。

您的代碼應閱讀:

app.controller('RandomCtrl', function($interval, $scope){ 
$scope.wood = 0; 
$interval(function(){ 
    $scope.wood++; 
}, 1000); 
}); 

之所以失敗默默是this.TEST ++返回NaN,而不是一個錯誤。