$scope.clickfunction = function(arg){
var url ="";
var httppromise = $scope.promiseufunction(arg); // return a http promise
httppromise.then(function(res){
if(res){
url ="path/"
$('#htmlelement').attr('href', url);
}else{
url="path2/"
$('#htmlelement').attr('href', url);
};
});
} //<---- this line execute before the inner function of promise.then
I have an anchor tag with ng-click that calls the above clickfunction function. I rely on the promise to resolve and update the href attribute, but I found that the end of function have reached before the innner function of promise.then(), and that causes my ng-click not work properly as i expected , href attribute updated after the ng-click event on href.
How can solve this,to make sure the inner function of promise work before reach the end of this function?
You could use ng-href to update the href once the promise is resolved. Here is a simulation of the concept.
var app = angular.module("sampleApp", []); app.controller("sampleController", ["$scope", "$timeout", function($scope, $timeout) { // Simulating the variable update at a later point. $timeout(function() { $scope.testUrl = "http://stackoverflow.com"; }, 3000) } ]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> <div ng-app="sampleApp"> <div ng-controller="sampleController as vm"> <a ng-href="{{testUrl}}">Google</a> </div>
So, keeping the above way as a reference, you could use ngHRef on the #htmlElement as use a model property that populates the value using a promise.
HTML
<a ng-href="newHref">Some anchor </a>
JS
$scope.clickfunction = function(arg) {
var url = "";
var httppromise = $scope.promiseufunction(arg); // return a http promise
httppromise.then(function(res) {
if (res) {
url = "path/";
} else {
url = "path2/"
};
$scope.newHref = url;
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.