Incorporating Angular to dynamically fetch data through AJAX and fill in content post-page render

As a backend API developer diving into AngularJS (version 1) for the first time with my current project, I have encountered a scenario that requires me to fetch server-side content dynamically post-render. The page is set up with ng-app="app" in the <html> tag and

ng-controller="BaseController as baseCtrl"
, rendering successfully.

The specific section of content (

{"status":"OK","id":"feed-whatsnew","content":"Unreliable source!"}
) needs to be loaded via ajax after initial render due to its unreliable and slow source. My challenge lies in using Angular to display this content within the specified
<div id="feed-whatsnew"> .. <div class="content"></div>..</div>
location and unhide it accordingly.

While Angular rendering logic is clear to me, secondary processes like this one remain somewhat mysterious. Although I would typically tackle this task with jQuery, I am determined to fully embrace the Angular framework rather than simply mimicking external libraries.

Answer №1

If you are working with Angular, one way to make AJAX calls to an external API is by using the $http provider. Here's a sample code snippet demonstrating how you can achieve this:

app.controller('BaseController', ['$http', function($http){
    var vm = this;
    vm.content = {};

    vm.fetchContent = function(){
        return $http.get('/my-api-endpoint').then(function(response){
            vm.content = response.data;
        }, function(response){
            console.error('Failed calling /my-api-endpoint ', response);
        });
    };

    // Load content initially
    vm.fetchContent();
}]);

When you call $http.get(..), it initiates an asynchronous request to the specified URL and returns a Promise object. Once the request completes, the Promise resolves, triggering the callback function passed to then([callback]). This callback then updates the vm.content variable in your controller with the response data.

For more information on the $http provider, refer to the official documentation.

To display the fetched content in your UI, you can use something like:

<span>{{baseCtrl.content}}</span>

The actual implementation may vary depending on the nature of your content. It's recommended to separate the fetchContent() function into an Angular service for better maintenance and organization.

Answer №2

AngularJS comes equipped with the powerful $http library for carrying out AJAX requests. For an easier understanding, refer to the documentation available at https://www.w3schools.com/angular/angular_http.asp

Outlined below are the logical steps:

  1. Inject $http in the controller's dependencies.
  2. Make a service call using $http.
  3. Upon successful response, assign the data to the $scope variable to make it accessible in the UI/HTML elements. The assignment may vary if you are utilizing the controller as syntax in the markup.

angular.module('app', [])
  .controller('BaseController', function($http) {
    var vm = this;
    vm.feed = null;

    _getDataFromServer();

    function _getDataFromServer() {
      var req = {
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        method: 'GET' //could be post/put etc
          //data: someJson -- if webservice need so
      };

      $http(req)
        .then(function(response) {
          vm.feed = response.data;
        }).catch(function(err) {
          console.log('some error occured!', err);
        });
    }
  });
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>

<div ng-app="app" ng-controller="BaseController as vm">

  <p>Using $http</p>

  <div id="feed-whatsnew" ng-hide="!vm.feed">
    <!-- use {{}} or ng-bind to bind the data -->
    <!-- use ng-hide to show/hide the content conditionally -->
    Title from Ajax Response: {{vm.feed.title}}
    <div class="content">
      Content:
      <p ng-bind="vm.feed.body"></p>
    </div>

  </div>

</div>

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

Showing the number of times a button has been pressed

I have written some HTML code to create a button and now I am looking for guidance on how I can use Vue.js to track how many times the button has been clicked. Here is what I have so far: <div class="123"> <button id = "Abutton&q ...

Manipulating Arrays in JavaScript: Techniques for Extracting Values Buried in Nested Objects

I am working with an array of objects that contain multiple "Book" objects with dynamic keys. My goal is to filter the objects in the array to only include those that have at least one new "Book" object. For example: const arr = [ { id: '123&ap ...

Integrating Watson Conversation with Oracle Database

Hello everyone, I am currently working on a project where I need Watson to fetch a response manually set from our Oracle Databases. To achieve this, I am using async to access the database sequentially and return the response. Initially, I faced an issue ...

Is it possible to prevent the late method from running during the execution of Promise.race()?

The following code snippet serves as a simple example. function pause(duration) { return new Promise(function (resolve) { setTimeout(resolve, duration); }).then((e) => { console.log(`Pause for ${duration}ms.`); return dur ...

The API is returning a successful response code of 200 when the HEAD and OPTIONS methods are utilized

My API is up and running smoothly with a GET method in express. This is the code for my API: app.get('/healthcheck', (_req, res) => { res.status(200).send({ state: 'Healthy', timestamp: new Date(), uptime: process.upti ...

The usage of nextTick in Vue.js and its role in updating components

Although I am a beginner with vue.js and have a basic understanding of it, I came across a sample code utilizing nextTick() today. Trying to comprehend its purpose led me to explore the documentation, which ended up complicating things further and leavin ...

Best Practices for Developing AngularJS Applications

After constructing a webpage with html, css, javascript, and jquery, I recently began studying Angular.js. I am curious to know if I need to reconstruct the entire site in order to adhere to specific angularJS standards, or if the additional elements for ...

"Incorporate an image into the data of an AJAX POST request for a web service invocation

I have been attempting (with no success thus far) to include an image file in my JSON data when making a call to a method in my webservice. I have come across some threads discussing sending just an image, but not integrating an image within a JSON data o ...

Does jQuery provide a counter function to ajaxComplete?

I'm curious if there exists a jQuery function that acts as the counterpart to ajaxComplete? I am looking for something that can be triggered before the ajax event, similar to beforeSend $( document ).ajaxComplete(function( event, xhr, settings ) { ...

Can someone explain the role of $ctrl in angularjs and when it is more appropriate to use $ctrl instead of $scope in

In this illustration, the variable $ctrl is utilized in the view <b>Heroes</b><br> <hero-detail ng-repeat="hero in $ctrl.list" hero="hero" on-delete="$ctrl.deleteHero(hero)" on-update="$ctrl. ...

Tips on how to retrieve a nested promise

Within my JavaScript function, I am utilizing rest calls and the responses to construct the payload for subsequent calls. Included below is some pseudo code exemplifying my approach. Although my code is currently functional, I am unsure how to properly ret ...

The browser is struggling to interpret the incorrect HTML content

I am looking for a way to create a function that can retrieve account data from my database and organize it in a user-friendly HTML table where users can make selections and modifications. The code I have so far is as follows: $.ajax({ url: "./dat ...

What are the steps to applying strike-through text in Vue.js?

I am currently working on a to-do application using Vue.js and I want to implement a feature where the text rendered in HTML has a line through it when the user checks an item off the list. Here is the snippet of my code: <html> <head> & ...

Benefits of utilizing minified AngularJS versions (Exploring the advantages of angular.min.js over angular.js, along with the inclusion of angular.min.js.map)

After introducing angular.min.js into my project, I encountered a problem. http://localhost:8000/AngularProject/angular.min.js.map 404 (Not Found) angular.min.js.map:1 Upon further investigation, I discovered that including angular.min.js.map resolve ...

Troubleshooting problem with populating data in Mongoose Database

Here is the code snippet: app.get("/cart", checkAuthentication, function (req, res) { Orders.find({ user: req.user._id }) .populate('user') .populate('order') .exec((err, orders) => { console.log(orders); ...

The error message "bind is not defined in chat.js on line 89 in React js" appears due to a ReferenceError

Greetings! I am new to working with React JS and have encountered an error in my code while developing a project. The console shows the following message: chat.js:89 Uncaught ReferenceError: bind is not defined(…) I am struggling to identify where I ...

Troubleshooting Problem with Accordion Size in CSS

I am facing an issue with a dropdown menu that I have created. The dropdown has parent and child rows to display controls, but the width of the Accordion is not stretching as expected despite being set to 100%. Using Chrome and Edge developer tools, I insp ...

Tips for effectively showcasing JSON in an Angular directive

I am facing an issue with my Angular app that utilizes ui-router. I have set up a service and directive, but I am unable to display JSON data. Surprisingly, it works perfectly fine without the directive when I directly display it in the main template (home ...

Javascript Error: Page reload interrupted by Broken Pipe IOError [Errno 32]

I am facing an issue with my javascript function that sends a signal to my flask app for recalculating figures using ajax. Upon successful figure production, I want to reload the page with updated figures by adding a version number to the filename (using & ...

A declaration of "import '***.css';" was located within an ECMAScript module file in the monaco-editor npm library

It's perplexing to me why the developers of monaco-editor included these statements, as they are actually causing errors in my browser such as: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME typ ...