2016-08-23 46 views
-1

我有MyExampleController控制器,它取决于某些可用数据。例如 - 如果myService.dataIsAvailable()true,那么myService服务中包含该数据。现在我访问某个控制器,我想检查它是否返回true,如果是,则为init();,否则如果它变成true,则触发init();。我该怎么做?当变量为真或成为真时执行功能

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

写我自己的代码

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); 

} 

]);

我希望它能工作。