[英]function end before angularjs promise resolve
$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
我有一個帶有ng-click的錨標記,可以調用上述clickfunction函數。 我依靠promise來解析和更新href屬性,但是我發現函數的結尾已經在promise.then()的內部函數之前到達,這導致我的ng-click不能按預期正常工作,href屬性在href上的ng-click事件之后更新。
如何解決此問題,以確保Promise的內部功能在此功能結束之前起作用?
解決承諾后,您可以使用ng-href更新href。 這是概念的模擬。
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>
因此,保持上述方式作為參考,您可以在#htmlElement上使用ngHRef作為模型屬性,該模型屬性使用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;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.