2017-02-23 21 views
0

角度コントローラメソッドから定期的にajaxリクエストを送信します。そのために私は以下のようなコードを書いています。角度コントローラメソッドで匿名メソッドを再帰的に呼び出す

var mainApp = angular.module('myapp',[]); 
mainApp.controller('controller', function($scope,$http,$window,$timeout) { 
    $('#radioBtn a').on('click', function(){ 
      $http({ 
       method:, 
       url:, 
       params:{parameters} 
      }).then(function(success){ 
      },function(error){ 
      }); 

      $timeout(function(){ 
       //how to call the anonymous function passed to $('#radioBtn     a').on() here. 
      },30000); 

     }); 

匿名メソッドをタイムアウト関数から呼び出す方法はありません。 this()の使用は失敗しています。

答えて

0

このようにしてください。

var mainApp = angular.module('myapp',[]); 
mainApp.controller('controller', function($scope,$http,$window,$interval) { 
    $('#radioBtn a').on('click', function(){ 


      $interval(function(){ 
       $http({ 
        method:, 
        url:, 
        params:{parameters} 
       }).then(function(success){ 
       },function(error){ 
       });  
      },30000); 

     }); 
+0

彼は代わりに$タイムアウトのここでの$間隔を注入しなければなりません。しかしこれはかなり危険です。新しい間隔がボタンを押すたびにトリガーされます。 – MikeOne

0

まずオフ:ng-clickディレクティブを使用し、そのような要素のクリックには結合しないでください - あなたはそれなし方がいいでしょう例を実際には、ちょうどさえ99%で、アプリケーション内のjQueryをロードしません。 。

秒:角度の$intervalサービスを使用します。以下のコードサンプルを確認してください。

angular.module('app', []) 
 
.controller('ctrl', function($scope, $interval) { 
 
    
 
    $scope.numbers = []; 
 
    $scope.startInterval = function() {  
 
    $scope.interval = $interval(function() { 
 
     $scope.numbers.push($scope.numbers.length); 
 
    }, 1000)  
 
    } 
 
})
<!DOCTYPE html> 
 
<html> 
 

 
    <head> 
 
    <script data-require="[email protected]" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script src="script.js"></script> 
 
    </head> 
 

 
    <body ng-app="app" ng-controller="ctrl"> 
 
    <button ng-if="!interval" ng-click="startInterval()">Start polling</button> 
 
    <div ng-repeat="number in numbers"> 
 
     {{number}} 
 
    </div> 
 
    </body> 
 
</html>

関連する問題