这是Angularjs $http wait for response
的后续问题由于我无法找到解决方案,我想我总是会返回一个承诺,让我的指令在promise.then()函数中完成工作。
$scope.getVCard = function(id){
var vcardKey = vcardKeyPrefix+id;
var vCardFromLS = localStorageService.get(vCardKey);
if(vCardFromLS){
var deferred = $q.defer();
deferred.resolve({data:localStorageService.get(vCardKey)});
return deferred.promise;
}
}
在我的指令中,我将其用作
(function(angular, app) {
app.directive('popOver',["$window","$http",function($window,$http){
return function(scope,elem,attrs){
elem.on('mouseover',function(){
console.log('mouseover');
var promise = scope.$apply(attrs.popOver);
promise.then(function(data){
console.log('promise then called');
console.log(data);
//logic here
});
console.log('in directive again');
console.log(data);
});
};
}]);
})(angular, app);
但是第一次没有调用promise.then()。它被调用并在后续鼠标悬停时正常工作。可能是什么问题?
我尝试在return deferred.promise
之前添加$ scope。$ apply()但我正在申请已经在进行中的错误。我在这里缺少什么?
答案 0 :(得分:1)
我相信这是因为你在回归之前就已经解决了它。我可能错了。
试试这个:
$scope.getVCard = function(id){
var vcardKey = vcardKeyPrefix+id,
vCardFromLS = localStorageService.get(vCardKey),
deferred = $q.defer();
if(vCardFromLS){
$timeout(function(){
deferred.resolve({data:vCardFromLS});
}, 100);
} else {
$timeout(function(){
deferred.reject();
}, 100);
}
return deferred.promise;
}