Performing an AJAX POST request using AngularJS

As I dive into AngularJS, one challenge I've encountered is integrating an AJAX call into my controller.js file. I've already managed to get the login controller up and running with the same service as this one.

Now, my goal is to fetch data from the server using a different method in my service and then pass it to the HTML in a specific format. However, I'm unsure about the correct approach to achieve this. The code snippet below represents my initial attempt, drawing inspiration from a previous Chrome Packaged App project where manipulating display on HTML was simpler due to a single JavaScript file. This time around, I'm navigating through controllers, services, and the app structure.

.controller('VFCtrl', function($scope, $stateParams, $http, $ionicLoading, $state, $sce) {
        $ionicLoading.show({
            template: 'Loading...',
            duration: 1000
        });

        $http.post('myService/mysite.aspx',{action: 'someMethodFromService', ParameterFromMethod: 'someValue'})
              .success(function (response) 
              {
                  var htmldata='';
                  for(i=0;i<response.length;i++)
                  {
                      var htmlInfo = '<li><div class=\'col\'><a href="'+ response[i].Id +'"><img width=\'100%\' height=\'auto\' src="'+response[i].Image + '" class=\'profile-img\' /><h3>' +response[i].Name+'</h3><p>'+response[i].Title+'</p></a></div></li>';

                      htmldata+= htmlInfo;
                  }
                    $("#vflist").html(htmldata);
              })
       //I don't wanna change how to submit data in my html in the success part
       //But if it MUST be change then I will.
              .error(function(data, status, headers){
                 console.log(status);
              });

    })

Answer №1

If you want to display a list of items from an array using AngularJS, you can utilize the ng-repeat directive. This directive allows you to loop through each item in the array and display them on the webpage. While the code snippet provided may not match your specific situation, it offers a basic example of how ng-repeat works: http://example.com/ng-repeat-demo.

The element where you include the ng-repeat directive will serve as the template for each repeated item. Any elements nested within this parent element will be duplicated for each item in the array. Check out the code pen link above for a live demonstration.

<ul>
    <li ng-repeat="item in vm.items"><span style="color:blue">{{ item.title }}</span></li>
<ul> 

Answer №2

Using Angular instead of jQuery would be more suitable in this scenario. It is not recommended to manipulate the DOM in an Angular controller.

To improve your code, you can follow the example below (please note that the JSON structure may vary from your original request):

var app = angular.module("sa", [])
app.controller('VFCtrl', function($scope, $http) {

  $http.get('http://jsonplaceholder.typicode.com/posts', {
      action: 'someMethodFromService',
      ParameterFromMethod: 'someValue'
    })
    .success(function(data) {
      $scope.posts = data;
    });
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="VFCtrl">
  <ul id="vflist">
    <li ng-repeat="post in posts">
      <a href="{{post.id}}">{{post.title}}</a>
  </ul>
</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

All the references were added, but Angular Material still refuses to cooperate

I am currently experimenting with Angular Material. I have added all the necessary references, but when I try to test it with an Angular Material button, the button doesn't appear on the screen. I suspect my issue is similar to the one discussed in th ...

How can I replace minified JavaScript files with non-minified versions in AngularJS for local development purposes?

What is the most effective approach to tackle this issue with AngularJS? I am currently working on an AngularJS application that consists of concatenated/minified JavaScript files. However, in my development environment, I prefer loading the non-concatena ...

The 'change' event in AJAX does not trigger when the value 'select value is assigned from PHP

I have a form that includes fields for city, state, and country. The goal is to automatically populate the state and country fields when a city is selected by retrieving data from a MySQL database using Ajax. However, I am facing an issue where the Ajax c ...

Tips on invoking a simple javascript function within a jasmine testing specification

I am currently facing an issue while writing test cases for a JavaScript method. My Jasmine framework is unable to call the JavaScript method and returns an error stating that the function is not defined. Controller Code snippet: (function () { "use stri ...

Tips for incorporating Jquery forms with PHP in multiple iterations of a while loop

I am attempting to run a while loop with jQuery form processing to prevent the page from refreshing. The current code seems to be working, however, the jQuery function is only applied to the first loop, with subsequent loops opening a new page instead. I ...

Watching for when the state changes in the AngularJS framework using the `$scope.$on('$stateChangeStart')` and

My AngularJs application has the functionality to detect a change in state (using ui.router) and prompt the user to save any unsaved changes. Currently, I am utilizing a confirm dialog for this task: $scope.$on('$stateChangeStart', () => { ...

Passing Data from Child Components to Parent Components in Vue.js

Looking for assistance with a component I have: <BasicFilter></BasicFilter> It contains a select element: <select @change="$emit('onSortName', $event)"> <option value="asc"> A..Z</option><opti ...

Even when the alert is dismissed, the `UnexpectedAlertOpenError` in Selenium Webdriver on Node.js continues to persist, causing unexpected

In my current setup, I am using Cucumber.js and Selenium Webdriver JS within a Node.js environment with Firefox as the chosen browser. The scenario involves testing a page that triggers an alert upon loading. While I have successfully created a Cucumber s ...

Displaying or concealing HTML elements using AngularJS while a modal is open

Looking for a way to display a loading spinner icon on my page when a user triggers a button that opens a modal, and then have the spinner disappear once the modal is open and its content has loaded. Currently, I've managed to make the spinner show up ...

Transforming the date from yyyy-mm-dd to Tuesday, the 25th

My variable is currently in the format: yyyy-mm-dd. I am looking to convert it into the format Tuesday 25th using JavaScript (specifically, the jQuery library). I attempted the following: var now = new Date('2013-06-25').format("l jS"); ...

Enhancing SVG graphics dynamically with JavaScript and ensuring compatibility across different web browsers

I am currently working on incorporating an element into an existing SVG file. Interestingly, the process runs smoothly on Chrome and Firefox but encounters issues on Edge. I aim for it to function seamlessly on the latest versions of all three browsers, wi ...

Setting the state of a component prior to rendering the next component using React-Redux

Whenever I click on a button, it leads me to another component. <Link to="/result"><button onClick = {this.setDealSizeAndType} name="patient">Calculate</button></Link> setDealSizeAndType({ target }){ const dealTypeName = ta ...

When using $http.get, it retrieves source code instead of displaying HTML content

Just diving into the world of AngularJS. I am using the $http service to make a request for an HTML page from localhost. However, instead of getting the desired result, I'm seeing the source code of the page. http_service.html <!DOCTYPE html> ...

Selenium waits patiently for my mouse to be in motion before proceeding

Struggling with a frustrating Selenium or webpage issue that requires me to physically move the mouse to continue execution. Despite trying various methods like simulating hover, clicks, and keyboard presses as well as using Thread.sleeps, nothing seems to ...

Type Error in Node.js Form Submission: Unable to define 'userId' property due to undefined value

After implementing login and registration features on a specific page in my application at views/employee/login.hbs, I encountered an issue. Upon entering registration details (email, username, password, and confirm password) and clicking the register butt ...

Using Knockout to bind an element to the selected value from a dropdown list

When using the following select, I am connecting it to an observable array. <select id="selectProtocols" data-bind="options: optionsAvailable, optionsCaption:'Selecione...', optionsText: 'SimpleDescription', optionsValue:'???&a ...

Is there a way to lower the cost with the same value that was used to raise it?

My goal is to adjust the price when the user clicks on the minus icon. However, I want the new price after decreasing to revert back to the initial price. quantityHandler: function (action, product) { // Increase or decrease quantity of product ...

unresolved string constant issue with a django template command

I encountered an issue with the code snippet below, which is resulting in an unterminated string literal error: $(function() { $('#addDropdown').click(function() { var $d = $('{{ form |bootstrap }}').fadeIn(). ...

troubles encountered in implementing JavaScript to toggle the display of content upon clicking a link

Here is the code below. Upon page load, the form data will be hidden. When clicking on the comment link, it will toggle the visibility of the form content. Clicking on the comment link again will show the hidden content once more. What is desired is to ha ...

Struggling with implementing map() inside another map() within the render() method in React TypeScript

I am looking to display messages and their corresponding replies in a React application using TypeScript. The messages are stored in one array within the state, while the replies are stored in a separate array. This is my current code which is not renderi ...