Creating a flash message following a redirect in AngularJS

Just diving into Angular JS and need some clarification. How can I set a flash message after a redirect?

Here's my scenario: I have a form where I save data using an HTTP request. Upon success, I navigate to another page using window.location(). Now, I want to display a flash message on that page.

JavaScript Code:

  $scope.Save_Details = function (id)
{  

$http.post(base_url+"sur/sur/save_data/"+id,{data:$scope.Surdata}).
success(function(response) {
   // $scope.successTextAlert = "Saved";  
  //  $scope.showSuccessAlert = true; 

    window.location = "#/surpage/nextpage?show_message= true";
});
}

New Update:

 var messageFlag = $location.search().show_message;
    if(messageFlag && messageFlag === 'true'){ 
    alert(messageFlag);
        $scope.successTextAlert = "Saved";  
        $scope.showSuccessAlertMsg = true; 
    }

View Template:

  <div class="alert alert-success" ng-show="showSuccessAlert">
            <button type="button" class="close" data-ng-click="switchBool('showSuccessAlert')">×</button> <strong> {{successTextAlert}}</strong>
        </div>

Could someone assist me with this issue?

Answer №1

Insert the following HTML code -

<!-- Display message text     -->
<div class=" panel-{{alerts.class}}" ng-show="alerts.messages" >
    <div ng-repeat="alert in alerts.messages track by $index" class="panel-body alert-{{alerts.class}}" >{{alert}}</div>
</div>

Add this code to your angular model -

$rootScope.alert = function(type,msg){
        $rootScope.message.push(msg);
        $rootScope.alerts = {
            class: type,
            messages:$rootScope.message
        }
    }

To display a success message -

$rootScope.alert('success',"Success !!!");

To show an error message -

$rootScope.alert('danger',"Error.");

Answer №2

If you want to display flash messages, consider using toastr JS.

Simply add the following JS code to your project to show a flash message.

To display a success message: toastr"success";

To display an error message: toastr"error";

Answer №3

UPDATE - Additional Code Included

yourAppModule.controller('displayMessageController', function($location){

   var displayFlag = $location.search().show_message;
   if(displayFlag && displayFlag === 'true'){
     // Display the message
   } 

});
  • When you go to the "nextpage" page, include a flag -> #/surpage/nextpage?show_message=true
  • In the controller for "nextpage", retrieve the value of the query string parameter "show_message" (inject $location into your controller and access the value using $location.search().show_message)
  • If the value is true, show the flash message

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

Keeping the state of a React component intact when navigating back from the router

Imagine you have two React components, A and B. As component A is displayed on the page, the user makes changes that affect some of the states within A. The user then clicks a button to navigate to component B using router.push('/b'). Subsequentl ...

What is the process of sending a $http.post request with data payload?

Can anyone guide me on how to submit form data using AngularJS? <form data-ng-submit="submitForm()"> <input type="text" data-ng-model="formData.text"/> <input type="email" data-ng-model="formData.email"/> <input type="subm ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

[Babel]: The option foreign.Children is not recognized

I encountered an error while building with the following script: webpack --colors --progress --watch --config --jsx-loader webpack.config.js Below is the content of my package.json file: { "dependencies": { // List of dependencies here }, "dev ...

Strategies for testing a split get() function using expressJS and jestJS to streamline unit testing

How can I define a get() route in an Express.js application for easy unit testing? To start, I extracted the get() function into its own file: index.js const express = require('express') const socketIo = require('socket.io') const Gp ...

Navigating through nested promises can be a daunting task within the world of JavaScript and Angular

Function 2 relies on the return of Function 1, while Function 3 uses both returns. How can I clean up this process? Currently, Function 3 is only giving me undefined values. Below are my 3 functions: Function1 $scope.nombreCompetencesATraiter = function ...

utilizing a pair of API requests within a personalized Alexa skill

I posted a question about integrating Alexa with the Steam custom skill API here, but I realize it might be too detailed for some to read through. In essence, my main question is: Can you make two separate API calls within the same block of JS code while ...

The error message "Cannot access 'id' property of undefined" is being displayed

I have a file named auth.js along with a middleware called fetchuser. The code provided below is causing an error that I cannot figure out. The error occurs during the process of sending a token to the user and verifying whether the user is logged in or n ...

Using NodeJS, pull JSON data from a JavaScript file and render it in a route file

I am currently utilizing Nodejs Express to work with a script that generates an array of objects from the Google API. My objective is to integrate this JSON data into my templates. How can I invoke the function within my script file from my route file? Be ...

Using the jQuery function in conjunction with Infinite Ajax Scroll provides a seamless scrolling

Utilizing jQuery for filtering options can enhance the user experience. For instance, selecting the "dead" option displays only rows with the status "dead". However, when implementing infinite Ajax scroll to load new data from the database, the filter sett ...

Employing API Integration with Node.js and AngularJS

Currently in the process of developing a language translating messaging application using Node and Angular. I have decided to utilize the Yandex API since Google Translate is not free. You can find more information about the API at www.yandex.com I am unc ...

Remove any nulls or undefined values from the object

I have developed a custom function that eliminates null and undefined values from an object. However, it seems to be mistakenly removing keys where the value is 0 as well. For instance: { key1: 'value1', key2: 0 } Even though it shouldn&ap ...

Error sending an email through the EmailJS backend JavaScript file

I am in the process of creating a route for my backend JavaScript Express server called server.js that will trigger an email to be sent to my Gmail account using EmailJS. When I attempt to use the following code: const SMTPClient = require("emailjs& ...

The React Router onEnter Function Error: "Maximum call stack size exceeded"

I'm currently checking if a specific configuration value is set, and if it is, I want to redirect to a child route. If not, the page should display as usual. However, when I implement this code, the URL updates as expected but then seems to get stuck ...

How to remove checkbox border using HTML, JavaScript, and CSS

Is it possible to remove the square border from a checkbox in HTML? ...

Adding an await tag to dispatch causes issues with performing a react state update on an unmounted component

I recently added an await tag to a redux dispatch and now I am encountering the following error message: index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your applica ...

Secure your text input with a masked Textfield component in Material-UI

I'm struggling to implement a mask for a TextField component, but so far I have not been successful. Although I attempted this solution, it did not work. No matter what method I try, the masking functionality just won't cooperate. Following the ...

Every single data attribute is unique for each element

Hello! I'm currently working on creating a sorting system for pictures, documents, and videos. Each div contains data-extension attributes, so my plan is to filter out all attributes that are jpg, gif, or png and make them visible while hiding the oth ...

Unable to get jQuery click and hide functions to function properly

Hello, I am currently working on a program where clicking a specific div should hide its own class and display another one. However, the code does not seem to be functioning correctly. Below is my current implementation: $("#one").click(function(){ v ...

Discrepancy in Code Outputs

Last night, I spent some time testing out code for basic functions. To preview my work, I used two platforms - Dash and JSFiddle. Everything seemed to be running smoothly on both sites. However, when I uploaded the code to my live website, none of the butt ...