Assigning an asynchronous href value to a link in AngularJS

I am looking to dynamically update the href of a link asynchronously. Consider the following HTML:

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

Here is the angular controller code:

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

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

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

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

    return deferred.promise;
  }
});

I want the link to always redirect to google.com, even on the first click. How can I synchronize the async call or assign the url so that it resolves properly?

View code in Plunker

Update:

After a suggestion from @Konstantin Krass, I tried using window.open(). However, this cannot be done asynchronously as it may trigger popup blockers. Instead, I attempted to open a new window on click (which wouldn't be blocked) and then update the URL to google.com once the promise is resolved. Unfortunately, this method does not work on iPad due to tab communication constraints. Any alternative solutions?

Answer №1

If you need to automatically redirect to a URL after clicking on a link, you can achieve this by using the built-in location.href method.

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

  $scope.resolveUrl = function() {
    async().then(function(resolvedUrl){
      location.href= resolvedUrl; //this will open the URL in the current page
      // If you want to offer a download or open in a new tab
      // you can do it like this: 
      // window.open(resolvedUrl);  
    });
  }

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

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

    return deferred.promise;
  }
});

Make sure to remove the {{url}} variable from your HTML code.

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

Answer №2

Are you looking for this specific solution? Click here

   app.controller('MainCtrl', function($scope, $q) {
  $scope.message = 'Create File';

  $scope.resolveUrl = function() {
    async().then(function(resolvedUrl){
       $scope.message  = "Download File"
      $scope.url = resolvedUrl;
    });
  }

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

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

    return deffered.promise;
  }
});
HTML:

  <body ng-controller="MainCtrl">
    <a ng-href="{{url}}"  ng-click="resolveUrl()" target="_blank">{{message}}</a>
  </body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can I use a custom font in an HTML5 canvas?

Has anyone had success importing a custom font for use in HTML5 canvas? I've been trying to do this by loading the font file on my computer, but all my attempts have failed so far. The canvas keeps showing the default font instead of the one I want to ...

Ways to increase the field count in PHP seamlessly with the help of JavaScript, jQuery, or AJAX, without the need to

Within my Yii form, there is a text field labeled certificate_name. I am looking to create a functionality where clicking on the plus icon will increment the text field by one and display it below the previous field. Below is the PHP code snippet I am usi ...

Issues with the OnChange function not properly functioning in duplicate input fields

I've designed a form that allows for adding or deleting rows, effectively cloning input fields. One of the input fields utilizes Jquery Ajax to retrieve its value. However, upon adding an extra row by cloning the parent row to generate a child row, th ...

How can we better protect an Angular route compared to using routeguard?

My project involves developing a Single Page Application using Angular 8. Within the SPA, I need to include a component with a form that should only be accessible to users with specific permissions. I initially thought of implementing a route guard for t ...

Tips on how to obtain the element reference while using v-if in Vue

I need to conditionally display a div inside a card that slides within a carousel. My current approach is to check if the ancestor element contains the active class, and then use v-if to decide whether it should be rendered or not. However, this method d ...

the div background is limited to the exact size of the text, not filling the entire

Currently, as I work on my web page using react.js, I'm facing the challenge of implementing a full-size background. Despite my efforts, the background only occupies the size of the text within the div. Here is the snippet of code I am working with: a ...

React.js application experiencing a lack of response from EventSource on-message function

Currently, I am in the process of migrating an established production application from jquery to react.js. The backend is built using Java (spring boot) and the existing app utilizes Server-Sent Events to push specific types of notifications from the serve ...

Access the system by logging in with a stored Google account

I have experience integrating "Login via Google account" on various websites. However, some sites like Zomato always display the option to login via Google as soon as you open them. They even show a list of Google accounts that I have previously logged i ...

What is the most effective way to extract information from a .txt file and showcase a random line of it using HTML?

As a newbie in HTML, my knowledge is limited to finding a solution in C#. I am attempting to extract each line from a .txt file so that I can randomly display them when a button is clicked. Instead of using a typical submit button, I plan to create a custo ...

Automatically generate numbering for an AngularJS ng-repeat list

I'm working on creating a student report list using Angularjs ng-repeat. My main issue is figuring out how to dynamically append numbering like an ordered-list to the generated list in the view. I am aiming for something similar to this: # | Name of ...

In JavaScript, the array is being passed as "undefined"

<html> <head> <script> function replaceLocation() { var locationArray= new Array(); locationArray[1,2,3,4]=document.getElementById("From").value.split(" "); document.getElementById("map").src="https://maps.google.com/maps?f=d& ...

Iterating through an array of objects within a Vuejs template

Consider the JSON data below: { "games": [ { "id": 1, "init_date": "2020-02-11T07:47:33.627+0000", "players_in_game": [ { "id": 1, "player": { "id": 1, "player": "Jack Bauer", ...

Utilizing the Embed tag to invoke URL requests repeatedly within an Angular application

I am currently developing a custom PDF viewer to display the PDF content fetched from an API response. The main issue I'm encountering is that the API call is being triggered multiple times, approximately 50 - 60 times or even more in some cases. Stra ...

Transforming an array of objects into a structured model

Upon successfully fetching JSON data, parsing it, and pushing it to an array, the current result is: [object, object] The desired transformation involves converting each object into the following data model: import { ItemModel } from './item.model& ...

Ways to populate an AngularJS array with text input from HTML

I'm new to AngularJS - attempting to create a simple todo-list application. I'm struggling with how to insert the text value from the input box into the 'todos' array. Here's my code snippet. HTML: <body ng-controller="MainCt ...

jQuery if statement appears to be malfunctioning

When the condition operates alone, everything works fine. However, when I introduce an 'and' operation, it does not function correctly. If only one of them is true, the code works. It also successfully takes input values. <!DOCTYPE HTML Code ...

AngularJS ng-repeat with dynamic ng-model is a powerful feature that allows for

I am attempting to dynamically generate the ng-model directive within an ng-repeat, but I am encountering a browser error. Our goal is to dynamically retrieve attributes of a certain type and set them in the DOM. The specific error I am receiving is: Err ...

What is the process for accessing browser API calls through Protractor?

Is there a method to identify if the necessary API has been activated by the browser? Can Protractor provide a list of APIs that have been called? ...

Putting a Pause on CSS Transition using jQuery

I am attempting to delay a CSS transition for an element by using a delay function, with an additional 0.2s applied to make it slide 0.2s later than the initial delay of the main wrapper. I am applying a class to give it a transition effect to slide from r ...

Utilizing AngularJS Directive to trigger a designated function upon change in an input file

My current project involves creating a scavenger hunt editor with various types of questions stored in an array. Each question can be of a different type, all displayed using ng-repeat. To achieve this, I utilize a JavaScript object representing a Questio ...