Reputation: 31
Here is what i expect to happen, i am using anulgarjs as controller
1.when a button is clicked, call the http post function and return a boolean value
2.the returned boolean is a checking condition
3.if ture, attach a url to a html element of href attribute , and clicked immediately
4.if false, a model pop up
$scope.checking = function(arg){
$http.post('path/').success(function(r){
// r is a boolean value
deferral.resolve(r);
});
return deferral.promise;
};
second function
$scope.secondfun =function(){
url= 'someurl'
$scope.checking().then(function(r){
if(r){
$('#htmlelement').attr('href', url);
}
else{
$('#somemodal').modal('toggle');
}
});
}
problem: the order is not as i expected model or url don't show up right after the button clicked. Instead, it shows up when i clicked the button again
Meanwhile , as i am not sure i've used the promise correctly , i tried something like this on the second function :
$scope.secondfun = function(){
url= 'someurl';
var bool = false;
$scope.checking().then(function(r){
bool = r;
});
if(bool){
$('#htmlelement').attr('href', url);
}
else{
$('#somemodal').modal('toggle');
}
};
problem: the if clause execute before the bool is assigned , bool is undefined
So , i just need something help to solve the problem
Upvotes: 1
Views: 134
Reputation: 2265
Just return the promise when checking
$scope.checking = function(arg){
return $http.post('path/');
}
And then use that promise as you are doing already
$scope.secondfun = function(){
url= 'someurl'
$scope.checking().then(function(r){
if(r){
$('#htmlelement').attr('href', url);
}else{
$('#somemodal').modal('toggle');
}
});
}
Upvotes: 3
Reputation: 4232
Try changing your checking function to this
$scope.checking = function(arg){
return $http.post('path/')
.then(function(r) {
return r;
},function(error){
return error;
});
}
Upvotes: 3