2014-04-24 97 views
0

我希望這個函數自動執行,但不工作。在Angularjs中自動執行函數

$scope.checkdate = function(){ 
    $scope.checked = 0; 
    $scope.unchecked = 0; 
    for(var i = 0; i < $scope.inventories.length; i++) { 
     if($scope.inventories[i].modified === $scope.time){ 
      $scope.checked = $scope.checked + 1; 
     }else if($scope.time2 !== $scope.time){ 
      $scope.unchecked = $scope.unchecked + 1; 
     } 
    } 
}; 
$scope.checkdate(); 

而且我的模板看起來像這樣:

<ul ng-init="checkdate()"> 
     <li><input type="checkbox" /> Checked {{checked}}</li> 
     <li><input type="checkbox" /> Unchecked {{unchecked}}</li> 
     <li><input type="checkbox" /> All</li> 
</ul> 
+0

您可以刪除NG-的init = 「了checkdate()」,因爲它已經被稱爲控制器內。它不回答問題 – thedjaney

+1

是否與上面的$ scope相關聯的控制器被實例化?你知道'$ scope.inventories.length'大於0嗎?雖然你的例子看起來有點不完整,但表面上你所要做的應該是有效的。 –

回答

1

首先,從Angular's documentationng-init

唯一的適當使用ngInit的是別名ngRepeat

的特殊屬性

所以你不應該在你的例子中使用它。

其次,您的init函數不應附加到$scope,因爲不需要它。它應該是控制器的私人功能。

第三,我們看不到控制器的定義。很可能你沒有創建一個,因此 - Angular不會關心其他的代碼。

所有的五分之一,你會得到在任何時間響應您是否已經創建了一個JS撥弄一個例子:)

無論如何,你的代碼應該是這個樣子(樣板)。應該幫助你。

HTML模板:

<ul ng-controller="MyController"> 
     <li><input type="checkbox" /> Checked {{checked}}</li> 
     <li><input type="checkbox" /> Unchecked {{unchecked}}</li> 
     <li><input type="checkbox" /> All</li> 
</ul> 

MyController.js

function MyController() { 
    $scope.checked = 0; 
    $scope.unchecked = 0; 

    // Define what needs to be done during initialization below. 
    function init() { 
     // I haven't checked your code but there are some uninitialized variables in there like $scope.inventories.... 
     for(var i = 0; i < $scope.inventories.length; i++) { 
      if ($scope.inventories[i].modified === $scope.time){ 
       $scope.checked = $scope.checked + 1; 
      } else if ($scope.time2 !== $scope.time){ 
       $scope.unchecked = $scope.unchecked + 1; 
      } 
     } 
    } 

    init(); // Call your private init function here. 
} 
+0

+1'ng-init'可能更好的命名爲'ng-repeat-init'之類的東西。似乎每個人都想誤用它,儘管文檔的意圖很好:) –

+0

是的,我將它廣泛用於惡意目的:D這部分是因爲它沒有用舊版本的文檔正確描述。 –

相關問題