我有以下两种方法,一种是http承诺,另一种是在加载iframe时在视图中触发的(带指令):
$scope.iframeOnLoad = function(){
console.log('the iframe is done loading');
};
$scope.getPage = function(uuid){
pagesFactory.getPage(uuid)
.success(function(data){
console.log('page data is done loading');
})
.error(function(error){
growl.error('This page does not exist.');
});
};
当两种方法都完成后,我想添加一些初始化魔法。但我无法找出等待两者的最佳方法。如果两个方法都在promises中,我可以等待它们,但是因为iframeOnLoad只在iframe完成加载时被触发..
该指令如下所示:
.directive('ngOnload', function () {
return {
restrict: "A",
scope: {
callback: "&ngOnload"
},
link: function(scope, element, attrs){
var location;
if(element.length > 0 && element[0].contentWindow){
location = element[0].contentWindow.location;
}else{
location = undefined;
}
element.on("load", function(){
scope.callback({
contentLocation:location
});
});
}
}
});
希望有人能赐教我:)
非常感谢。
答案 0 :(得分:0)
为什么不将iframeOnload
转换为承诺
$scope.iframeOnLoad = function(){
return $q(function(resolve, reject) {
....on("iframeloadedEvent", function() {
resolve("iframeloaded")
})
...
$q.all([$scope.iframeOnload(), $scope.getPage()]
.then(magic)
如果您有进一步的问题,请尝试
var p1 = $q(function(resolve, reject) {
$scope.iframeOnLoad = function(obj) {
resolve(obj);
};
}
$q.all([p1, $scope.getPage]
.then(magic)
我觉得在一个闭包中设置iframeOnload是不舒服的,所以我不确定它是否会起作用。其他人可能能够提供更优雅的解决方案
答案 1 :(得分:0)
答案 2 :(得分:0)
将回调函数传递给您的服务,例如
myservice.getuser(data,function(response){
//response data
});
在服务中
getuser:function(data,callback)
{
$http()
.success(response){callback(response)}
.failure(response){callback(response)}
}
或 你可以用这个
var deferred = $q.deferred();
$http(api url and method)
.success function() {
deferred.resolve();
}
.failure function() {
deferred.reject();
}
return deferred.promise;