Creating a Self Closing Alert Message in AngularJS: A Step-by-Step Guide

Just getting started with AngularJS and looking to create a self-closing message. How can this be accomplished?

I'm aiming for similar results as the question found here:

How to Automatically Close Alerts using Twitter Bootstrap

However, I want to achieve this using AngularJS only.

Currently, I have tried using the following code with an array but it's not working as expected:

 $timeout(function () {
        stack.push(messages.pop());
        checkStack();
    },5000);

Answer №1

If you want to achieve similar functionality without relying on jQuery, consider using a directive along with the $timeout function. This approach allows you to create custom alerts in AngularJS.

app.directive('myAlert', function($timeout){
  return {
    scope: {
      message: '@',
      isVisible: '='
    },
    link: link,
    restrict: 'E',
    replace: true,
    template: '<div ng-if="isVisible" class="alert">{{message}}</div>'
  }

  function link(scope, element, attrs){
    scope.isVisible = true;

    $timeout(function (){
            scope.isVisible = false;
            }, 5000);

  }
});

For an example implementation, check out this Plunker demo: http://plnkr.co/edit/2ApTMAHjvMsq8OE1cInB?p=preview

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

Encountering a getMacChromiumEdgeDriverArchitecture error while using wdio/selenium-standalone-service

As I continue to learn WebDriverIO and adjust to MacOS, I encountered an error while trying to execute a spec file using "npm run test:wdio". The error message is as follows: > [email protected] test:wdio /Users/vinicius.correia/Desktop/dev/automat ...

Step-by-step guide on activating a controller function following an Animation in Angular JS

I have hit a roadblock trying to connect a series of animations with a controller action. My goal is to: 1. click on a button/div, 2. Trigger an animation, 3. Once the animation finishes, execute a function in the controller to reset the button/div. I&a ...

Locate the final element within an array using JavaScript

Provided with a file path like new/lib/java.exe, I am looking to eliminate the root folder 'new' and structure the new path as lib/java.exe. Challenge: After my attempts, I am left with the path as lib/java.exe/ which includes an unwanted "/". I ...

Are there any situations in which subscribing to an RXJS Observable does not result in either a success or error response

I have a question rather than a problem to resolve. I am curious if there is a scenario where neither "Success" nor "Error" are triggered. When making a POST call to "/logout", the expected response is an HTTP status code of 200 with an empty body. impo ...

How to modify the incoming request URI in AngularJS

Within my AngularJS application, the URL pattern I typically use is: https://myapp/#!/mypage However, I am now faced with a situation where I need to accommodate an incoming request from another application using this URI: https://myapp/myotherpage It&ap ...

What is the best method to access the query string or URL within an AJAX page?

I recently discovered how to extract query string parameters from this helpful resource. However, I am facing difficulty retrieving the URL within the requested page via ajax. For instance: <div class="result"></div> <script> $(func ...

What is the process for transforming JSON into a different format?

Currently, I have a JSON array structured as follows: var data = { report: [ { Name: "Nitin", comment: [ { count: 0, mName: "Feb" }, ...

Issue with Jade not displaying external JSON data

I am struggling with a jade template that is supposed to display all possible solutions from the QPX Express search request: { kind: 'qpxExpress#tripsSearch', trips: { kind: 'qpxexpress#tripOptions', requestId: 'RwDOf6H ...

Enhance the input choices in Angular JS by incorporating additional input alternatives

Currently, I am working on a form that requires selecting a country from a list to add shipping costs to the total. This particular form utilizes the ngCart directive and requires the use of ng-click to send this information to the directive. The issue I ...

The i18next plugin initialization does not include the implementation of 'resGetPath'

I'm having trouble setting up the resGetPath attribute in i18next to access translation.json files locally. When I initialize the plugin with the resources object, everything works fine. However, when using the resGetPath attribute, I can't seem ...

Upon installing a global npm package, the system encountered an error stating: 'File or directory not found: ENOENT'

After successfully publishing my first Node.js CLI tool package on npm, I encountered an issue when trying to test it by installing it locally. The warning message "Error: ENOENT: no such file or directory" kept showing up. Steps for Reproduction To start ...

The issue of why iterating over an array of objects does not function properly in React JS

P.S: I have made some modifications to the code below. Extracting the doctor's value from JSON data, updating the state, and then mapping it to print out the values. Initially, there is only one doctor, but in the future, there could be more than one ...

Troublesome Issue with ngAnimate and ngHide: Missing 'ng-hide-animate' Hook Class

I am working on a case where I need to add animation to a DOM object using the ngHide directive: Check out this example here Within this scenario, I have an array of JSON objects: $scope.items = [ {"key": 1, "values": []}, {"key": 2, "values": [ ...

Sending SQL information to an Angular interface using NodeJS

I'm struggling to figure out how to display data from a MySQL server using Node. Although I can successfully retrieve the data and log it in the CLI when running "node server.js", I am unsure of how to send this data to my Angular view. Console loggin ...

The XMLHttpRequest response states that the preflight request did not meet the access control check requirements

I am attempting to subscribe to a firebase cloud messaging topic by sending an http post request. var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState ...

Searching in AngularJS yields unexpected results beyond what was anticipated

I am attempting to retrieve all the users from my Rails application This code is in my Javascript file: var app = angular.module('app'); app.factory('User', function($resource) { return $resource('/users/:id', {id: &apos ...

Unable to process form submission using Ajax in ASP.NET MVC

I'm having trouble with submitting a form using ajax and opening a modal dialog after the ajax function is successful. Whenever I click the submit button, the process doesn't complete. Where could the issue be, in the ajax method or somewhere el ...

Displaying a two-dimensional array from a JSON file using AngularJS ng-repeat

Looking at this HTML file, I am trying to display a 2D array from the json-$scope.listOfIngredient <div class="ingredientMapping" ng-repeat="IngredientMapping in listOfIngredient track by $index"> <ul> <!-- BEGIN: Inner ngRep ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

What is the best way to retrieve data from MySQL for the current month using JavaScript?

I need to retrieve only the records from the current month within a table. Here is the code snippet: let startDate = req.body.startDate let endDate = req.body.endDate let result = await caseRegistration.findByDate({ p ...