[英]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.