我有MyExampleController
控制器,它取决于某些可用数据。例如,如果myService
为myService.dataIsAvailable()
,则true
服务中包含该数据的服务。现在我访问某个控制器,我想检查它是否返回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 :(得分: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
脚本。
答案 1 :(得分:0)
写下我自己的代码和平
var initInterval = null;
var timeMs = 100;
initInterval = $interval(function () {
if (myService.dataAvailable()) {
$interval.cancel(initInterval);
init();
}
}, timeMs);
答案 2 :(得分:0)
您可以观察服务中的数据,并在数据变为true时执行init函数。因此代码将如下:
angular.module( 'angularUiApp') .controller( 'MyExampleController',[ '$间隔', '为myService', function($ interval,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);
}
]);
我希望它能奏效。