ng-click - triggers a function and then redirects to another page

I'm facing a small issue.

I am trying to set up an ng-click event that redirects, but before the redirect happens, I need to send some data through post request.

Here is my HTML code :

<a href="/test" ng-click="updateData($event)">Go</a>

This is my angular updateData function :

$scope.updateData = function($event){

   $event.preventDefault();

   $http.post(someAddress, $scope.data)
      .success(function(){
          // on success redirect
      });
   };

I came across something like this scope.$eval(clickAction); but I'm not sure how to implement it in my case.

I need to use JS for the redirect as I have 2 different forms that require separate handling.

Answer №1

<a href="/example" ng-click="fetchData($event, this.href)">Click Here</a>


$scope.fetchData = function($event, link){
   $event.preventDefault();

   $http.post(anotherAddress, $scope.data)
      .success(function(){
          // redirecting on successful response
          location.href = link;
      });
   };

Answer №2

It is recommended to redirect from a JavaScript function instead of relying on the href attribute. In this case, there is no need for $event.preventDefault();.

HTML Markup

<a href="" ng-click="updateData()">Go</a>

JavaScript Code

 $scope.updateData = function(){
    $http.post(someAddress, $scope.data)
    .success(function(){
      // Redirect on success
      $location.path('/test'); // Redirecting from here
    });
 };

Answer №3

If you need to perform complete redirects, consider using the code snippet below:

window.location.href = "http://exampleurl.com";

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

Step-by-step guide to utilizing instance functions in AngularJS

Recently I started working with angular in my project but I'm struggling to figure out how to access instance functions from the original code. Here is a snippet of my function: $scope.collapsedrow = true; $scope.PlusClick = function(event) ...

Pinia not properly updating state with an array of objects in Vue 3

Currently working with Vue 3 and Pinia, I have a store called cards.js structured like this: import { defineStore } from 'pinia' import { useLanguageStore } from './language' import axios from 'axios' export const useCardsSt ...

Looking for a way to enhance image resizing animations in JavaScript for a seamless visual

Having two images inside a container means not knowing their size in advance after uploading. The resize function used helps fit the images within the container, but the animation appears choppy. Is there a way to improve its smoothness? $(window).load(f ...

Utilize JavaScript to split an HTML div section using a delimiter

On my current webpage, I have a gallery of images accompanied by captions. <img>image1</img> <div class="caption">IMAGE 1 TITLE: Subtitle</div> <img>image2</img> <div class="caption">IMAGE 2 TIT ...

Issues with the functionality of socket.io and node.js are causing problems

Currently, I am experimenting with building apps using socket.io and node.js. Specifically, I am working on a basic "log in" application, but it seems to be encountering some issues. Every time I launch the app, a "404 not found" message appears in the Chr ...

Create a Boxplot chart using Chart.js that dynamically adjusts the minimum and maximum values to allow for additional space on either

I am utilizing chartjs v2.9 for creating a boxplot and my code structure is as follows: function generateRandomValues(count, minimum, maximum) { const difference = maximum - minimum; return Array.from({length: count}).map(() => Math.random() * ...

Fixed-positioned elements

I'm facing a small issue with HTML5 that I can't seem to figure out. Currently, I have a header image followed by a menu div containing a nav element directly below it. My goal is to make the menu div stay fixed when scrolling down while keeping ...

Browser freezing due to large response when appending data with AJAX

I have been developing an application that retrieves numerous records from a database and displays them in a table. This process involves making an AJAX call and appending the new records to the existing ones. The number of records can vary greatly, rangi ...

What is the best way to position a success alert in the center of the page?

My application displays a success alert using Bootstrap when a user updates or inserts data and the return value is 1. However, this alert appears at the end of the page, and I want it to be positioned in the middle of the page or at the footer of a specif ...

Guide on utilizing Twig and Symfony2 to generate a confirmation pop-up box for redirecting users to a specific page

When clicking on the delete button, I want to ensure that an alert pops up to confirm the action. In my previous experience with CodeIgniter, I had a solution that worked effectively: Button: <td><a class='Right btn btn-danger' onClic ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

Switching CSS Unicode to JavaScript

I've been using a few emoji unicodes that work great in CSS: content: "\f410" content: "\f2d1" I attempted to display them with JavaScript, but unfortunately, I was unsuccessful. Any suggestions you have would be ...

Implementing ElasticUI with AngularJS through efficient dependency injection

Hey there, I'm seeking guidance on how to implement dependency injection in Angular. Currently, I am utilizing ElasticUI which can be found at this link: https://github.com/YousefED/ElasticUI In order to specify the index-name, it must be defined wi ...

Having trouble with the full-screen feature not functioning properly?

I am currently in the process of creating a custom video player and I need to include a full-screen button. However, when I click on it, the video does not expand to fill up the entire screen. I am using javascript, css3, and html5 for this project. Any as ...

Radio input not refreshing in alignment with model modifications

Upon reviewing Angular's documentation regarding input[radio], I discovered that it is possible to link each radio button to a specific value in the scope/controller using ng-value. However, I am facing difficulties in ensuring that my view accurately ...

AngularJS - Issue with ng-mouseover not triggering controller function

I am struggling to get a function to trigger when my button is hovered over. Despite writing what I believe is the correct code, the function from my controller is not being called. Can anyone spot the issue? Below is the JavaScript code: angular.module( ...

Using a forEach loop within an Else statement is ineffective

I've encountered an issue while trying to merge two arrays and create a new one. It seems that my forEach loop inside the else statement is returning undefined. I'm unsure if I made a mistake in my approach or if forEach is not meant to be used w ...

When loading a page in NodeJS and Express, there are no initial displays, but upon refreshing the page, all data is successfully retrieved

Struggling to solve this issue that has been lingering for a while. I'm currently working on a project where a remote JSON file is loaded into memory, parsed, and the results are displayed on the page (using pug). Everything seems to be working fine ...

Oops! Next JS encountered an unhandled runtime error while trying to render the route. The

I keep receiving the error message Unhandled Runtime Error Error: Cancel rendering route Within my navBar, I have implemented the following function: const userData={ id:1, email: "", name: "", lastName: "", ...

Bring together a set of elements within a collection of identical entities that contain corresponding key-value pairs by utilizing JavaScript

Looking at the object below: a = [ {id: 1, comp: 'ans', stat: 'www', value: ['1', '2']}, {id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b']}, {id: 3, comp: 'ans', ...