2016-08-23 4 views
-1

MyExampleControllerコントローラは、利用可能な特定のデータに依存します。例えば、myServiceサービスの場合、myService.dataIsAvailable()trueの場合、そのデータが入っているサービス。今度は特定のコントローラにアクセスし、trueを返すかどうかを確認したい場合はinit();、それ以外の場合はtrueになると、init();が発生します。どうすればいいのですか?変数がtrueまたは真となったときに関数を実行

angular.module('angularUiApp').controller('MyExampleController', function()  { 
    function init() { 
     console.log('do some stuff'); 
    } 

    // init single time only when myService.dataIsAvailable() is true or execute init() when myService.dataIsAvailable() becomes true. 
    init(); 
}); 

答えて

0

はあなたがサービスからのデータを監視し、データが真になったときにinit関数を実行することができ、コード

var initInterval = null; 
var timeMs = 100; 

initInterval = $interval(function() { 
    if (myService.dataAvailable()) { 
     $interval.cancel(initInterval); 
     init(); 
    } 
}, timeMs); 
0

angular.module('angularUiApp').controller('MyExampleController', ['myService', function(myService)  { 
    function init() { 
     if(!myService.dataIsAvailable()){ 
      setTimeout(function() { // try again later - you could do that with a while loop also, whatever suits your needs 
          init(); 
      }, 400); 
     else{ 
      // do stuff 
     } 
     } 
    } 

    // init single time only when myService.dataIsAvailable() is true or execute init() when myService.dataIsAvailable() becomes true. 
    init(); 
}]); 

p.sを待つ:myServiceスクリプトがコントローラスクリプトの前にロードされていることを確認してくださいあなたのコントローラにあなたのサービスを注入し、必要な値をチェックし、そうでありません。

幸運:)

0

の私自身の平和を書きました。そうコードはのようになり:

angular.module( 'angularUiApp') .controller( 'MyExampleController'、[ '$間隔' 'myServiceという' 関数($間隔、myServiceという){

var checkingForData; 

    function init() { 
     console.log('do some stuff'); 
    } 

    var doSomeTask = function(){ 
     /* init single time only when myService.dataIsAvailable() is true or execute init() 
     when myService.dataIsAvailable() becomes true. */ 
     init(); 
     if(checkingForData) $interval.cancel(checkingForData); // cancel interval after getting data 
    }; 

    checkingForData = $interval(function(){ 
     if(myService.dataIsAvailable()){ 
      doSomeTask(); 
     } 
    }, 1000); 

} 

]);

私はうまくいきたいと思います。

関連する問題