Guide on retrieving JSON information through an AJAX request within an AngularJS Bootstrap modal

I am eager to implement the following functionality: a button that triggers a dialog/modal from Angular Bootstrap which showcases a loading indicator as the application retrieves JSON data from the server. Once the data is fetched, it should be displayed within the dialog content.

My current plan is to create a dialog template that includes code for parsing the JSON data, such as utilizing ng-repeat to present it in a list format.

However, I have a few uncertainties:

  1. Where should I include a loading indicator (such as spin.js) during this process? I presume I would need to reference a specific div within the dialog template from the controller.
  2. When should I make the AJAX call to retrieve the data?
  3. How can I pass the fetched data to the template for parsing and display?

Answer №1

If you want to display a template in a dialog using AngularUI, you don't have to manually load it. The $dialog service allows you to provide a static template or a template URL. The URL can return any data, as it triggers a GET request via AJAX and populates the dialog with the retrieved information. This request is locally cached for subsequent calls, enhancing performance.

Below is a basic example to help you get started:

Javascript

angular.module('app', ['ui.bootstrap.dialog'])
    .controller('Ctrl', function($scope, $dialog, $window) {
        $scope.open = function() {
            var options = {
                backdrop: true,
                keyboard: true,                    
                controller: 'DialogCtrl', 
                templateUrl: 'path/to/view' 
            };
            var dialog = $dialog.dialog(options);
            dialog.open().then(function(result) {
                if (result === 0) {
                    $window.alert("Cancel pressed");
                }
                else if (result === 1) {
                    $window.alert("OK pressed");
                }
            });
        };
    })
    .controller('DialogCtrl', function($scope, $http, dialog) {
        $scope.close = function(result) {
            dialog.close(result);
        };

        $http.get('/path/to/service')
            .success(function(response) {
                $scope.items = response;
            });
    });

Main HTML

<div ng-app="app" ng-controller="Ctrl">
  <button ng-click="open()">Open dialog</button>
</div>

View HTML

<div class="modal-header">
  <h3>Title</h3>
</div>
<div class="modal-body">
  <p ng-repeat="item in items">{{ item }}</p>
</div>
<div class="modal-footer">
  <button class="btn" ng-click="close(0)">Cancel</button>
  <button class="btn btn-primary" ng-click="close(1)">OK</button>
</div>

This Plunker script showcases the functionality discussed.

Update: The example code has been updated to illustrate how you can dynamically alter the content of the dialog box.

Answer №2

"The modal directive makes use of the $dialog service to easily create modals that already exist in your DOM, eliminating the need to create separate partial views and controllers.

This directive also inherits global options from $dialog."

To view the available bootstrap dialog options, visit the following URL:

http://angular-ui.github.io/bootstrap/#/dialog

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

tips for concealing the shadow of a draggable div during the dragging process

I am facing an issue with a draggable div. When I drag the div, the shadow also moves along with it. I want to find a way to hide this shadow while dragging. <div draggable="true" (dragstart)="mousedown($event)" (drag)="dra ...

When trying to update a MySQL database, the ampersand is appearing as &amp;amp; instead of the expected &

Currently, I am in the process of creating an administrative section that will allow for easy management of information displayed on the main website. This section will enable users to add, update, and delete content using just one page. Most of my script ...

An issue arises when attempting to iterate over an object literal using ng-repeat in AngularJS

I am currently learning angular js and practicing filters. I have successfully been able to iterate over an array of objects, but when trying to work with objects within objects, my browser is throwing an error: "Uncaught SyntaxError: Unexpected token" &l ...

Steps to set up Feathers instance in Jest environment once

When running Jest tests, I want to utilize only one instance of feathers "app" throughout. This is how I currently import app in each test: const app = require('../../src/app'); describe(`service`, () => { it('registered the service&ap ...

Modify the CSS style of the select label and change the color of the currently selected option in MUI

For the past few days, I've been facing challenges with implementing MUI components while working on a page for a React app. I'm almost finished with my project, but there are 2 key things missing... On my page, I have utilized a Select and an ...

Retaining original input value even when validation is applied with input type="number"

Encountering an unusual scenario while using angularJs and input type="number". It seems that if the initial value of an input falls outside the specified min and max range, the value gets wiped out. To better visualize the issue, I created a fiddle - htt ...

Linking a live-generated HTML to the scope's data model

Encountering a roadblock…. In my project, I have a popover element that requires specific content to be defined. The content can either be a String representing HTML or a function that generates the HTML. The HTML in the popover should display a ...

Find the time matching in a time string using Javascript

I need to extract the time in the format "HH:MM:SS" from a string like "HH:MM:SS CEST". How can I achieve this without including any additional strings such as CEST? ...

What is the best way to showcase a specific column from a dataset using Vue.js and axios?

Hey there, I'm still getting the hang of all this and haven't quite mastered the jargon yet. Here's what I need help with: I managed to retrieve data from my SQL database using axios, and when I check in (f12) - network - preview, it shows: ...

Setting the cache to false during an httpget request in an mvc4 controller action: tips and tricks

My httpget request to a controller action looks like this: $.get('/Course/ExplanationCorrect/', postData, function (data) { $('#SurveyDiv').html(data); }); While it works on all other browsers, I'm facing an issue with IE10 o ...

The Node.js Express undefined callback function is causing issues

I'm currently working on a personal project and I don't have much experience with nodeJS. My goal is to retrieve remote JSON data, generate statistics based on that data, and display it. However, I am encountering some issues with the callback fu ...

Encountering the "EHOSTUNREACH" error message while attempting to establish a connection to an API through the combination of Axios and Express

Exploring the capabilities of the Philips Hue Bridge API, I delved into sending requests using Postman. To my delight, I successfully authenticated myself, created a user, and managed to toggle lights on and off. Verdict: Accessing the API is achievable. ...

Having difficulty receiving a response from an AJAX call within the success function

After browsing through this stack link Ajax response not calling success:function() when using jQuery 1.8.3, I'm puzzled as to why the success function is not invoked when I uncomment the dataType line. It seems that setting dataType = JSON prevents t ...

Encountering an issue with DateTimeField being undefined in a React.js application

I encountered an issue stating that DateTimeField is not defined while attempting to create a date picker in react + bootstrap. I referred to the following URLs for assistance: https://github.com/Eonasdan/bootstrap-datetimepicker Link to my code s ...

Utilizing ngModel within the controller of a custom directive in Angular, instead of the link function

Is there a way to require and use ngModel inside the controller of a custom Angular directive without using the link function? I have seen examples that use the link function, but I want to know if it's possible to access ngModel inside the directive ...

The event is being triggered on two separate occasions

Hey there! I'm trying to bind the onclick event to both a parent and child element using the same method. However, I'm running into an issue where the event is being fired twice. Any suggestions on how to prevent this from happening? <div id= ...

Transmit messages from server (via Expressjs routing) to the client

I am looking for guidance on how to effectively send messages from the server to the client and incorporate this functionality into routes/index.js within my mean stack project. Can anyone provide insights on using socket.io in this context?: router.post( ...

Adjusting the transparency of the object's interior

I used the side property to give my object an interior, but it also reflects the exterior: let material = new THREE.MeshStandardMaterial({side: THREE.DoubleSide}); https://i.sstatic.net/oikad.png https://i.sstatic.net/Vb03K.png Is there a way to red ...

The Angular integration with Semantic UI dropdown does not display the selected value clearly

I have put together a small example to demonstrate the issue. http://plnkr.co/edit/py9T0g2aGhTXFnjvlCLF Essentially, the HTML structure is as follows: <div data-ng-app="app" data-ng-controller="main"> <select class="ui dropdown" id="ddlStat ...

How to extract data from URLs in Angular

Looking into how to extract a specific value from the URL within Angular for parsing purposes. For example: http://localhost:1337/doc-home/#/tips/5?paginatePage=1 The goal is to retrieve the value "5". HTML snippet: <a href="#/tips/comments/{{ tip ...