gpt4 book ai didi

javascript - AngularJS 异步将 href 分配给链接

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:32:38 27 4
gpt4 key购买 nike

我需要异步更新链接的 href。假设我有这个 html:

<a ng-href="{{url}}" ng-click="resolveUrl()" target="_blank">click me</a>

还有这个 Angular Controller :

app.controller('MainCtrl', function($scope, $q) {
$scope.url = '#';

$scope.resolveUrl = function() {
async().then(function(resolvedUrl){
$scope.url = resolvedUrl;
});
}

function async() {
var deffered = $q.defer();

setTimeout(function() {
deffered.resolve('http://www.google.com');
}, 1000)

return deffered.promise;
}
});

即使是第一次,我也需要链接才能转到 google.com。如何同步异步调用或如何分配 url 以便异步函数解析?

Code in plunker

编辑:

正如@Konstantin Krass 指出的那样,我可以使用 window.open()。但我不能异步使用它,因为浏览器会弹出阻止新窗口。所以我尝试打开另一个点击窗口(未被阻止),然后在 promise 得到解决后,我将打开的窗口的 url 更新为 google.com。编辑过的 plunker 是 here .不幸的是,这在 iPad 上不起作用。在 iPad 上,页面 url 不会更新,因为在 iPad 上,选项卡无法相互通信。有什么想法吗?

最佳答案

如果你想计算url并在点击后重定向到url,你可以在收到url后使用原生的location.href

app.controller('MainCtrl', function($scope, $q) {     

$scope.resolveUrl = function() {
async().then(function(resolvedUrl){
location.href= resolvedUrl; //this would open the url in the current page.
// if you want to offer a download or move
// into new browser tab you can go like this:
// window.open(resolvedUrl);
});
}

function async() {
var deffered = $q.defer();

setTimeout(function() {
deffered.resolve('http://www.google.com');
}, 1000)

return deffered.promise;
}
});

并从 html 中删除 {{url}}

<a ng-click="resolveUrl()">click me</a>

关于javascript - AngularJS 异步将 href 分配给链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24449469/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com