Can someone help me figure out the issue with my Angularjs ng-repeat implementation?

After spending hours trying to figure out why something so simple is not working, I'm at a loss.

Testing with a dummy list proves the functionality works, but when I connect my server-side data source, it fails. The JSON returned from the AJAX call is identical to that of the dummy list.

Where am I going wrong?

Here's a link to a working example with a dummy list: http://plnkr.co/edit/6nBkdBpPVqQ2P8u2BEeY

The server side is an .NET MVC 4 app.

HTML:

 <div data-ng-controller="currencyController">
     <ul>

       <li data-ng-repeat="currency in currencies"><span>{{ currency.CurrencyCode}} - </span><span>{{ currency.CurrencyName }}</span>
   </li>

     </ul>
 </div>

JS:

var currencyTools = angular.module('currencyTools', []);

currencyTools.controller('currencyController',function(currencyService,$scope) {
   var path = 'currency/GetCurrencies';
   currencyService.getAllCurrencies(path, function (jsonResult) {
        $scope.currencies = jsonResult.data;
    });
   // $scope.currencies = dummyList(); //if i uncomment this it works
})





currencyTools.factory('currencyService', function () {
    var service = {
        getAllCurrencies: function (path, callback) {
            var result = $.ajax({
                url: path,
                type: 'GET',
                dataType: 'json',
                data: '',
                contentType: 'application/json; charset=utf-8',
                success: function(json) { callback(json); }
            });
            return result;
        }
    };
    return service;
});


function dummyList() {
    return [
    {  "CurrencyCode": "BAM", "CurrencyName": "Bosnia-Herzegovina Convertible Mark" },
    {  "CurrencyCode": "BBD", "CurrencyName": "Barbadian Dollar" }, 
    {  "CurrencyCode": "BDT", "CurrencyName": "Bangladeshi Taka" },
    { "CurrencyCode": "BGN", "CurrencyName": "Bulgarian Lev" },
    {  "CurrencyCode": "BHD", "CurrencyName": "Bahraini Dinar" },
    {  "CurrencyCode": "BIF", "CurrencyName": "Burundian Franc" }, 
    {  "CurrencyCode": "BMD", "CurrencyName": "Bermudan Dollar" }, 
    {  "CurrencyCode": "BND", "CurrencyName": "Brunei Dollar" }, 
    {  "CurrencyCode": "BOB", "CurrencyName": "Bolivian Boliviano" },
    {  "CurrencyCode": "BRL", "CurrencyName": "Brazilian Real" }, 
    {  "CurrencyCode": "BSD", "CurrencyName": "Bahamian Dollar" }, 
    {  "CurrencyCode": "BTC", "CurrencyName": "Bitcoin" }];
}

Answer №1

It seems like there are a few issues happening in this code snippet.

  1. $.ajax is returning a promise, not a value, so the getAllCurrencies method should be set up to handle promises by subscribing to its success() function. However, it's important to note that using JQuery for AJAX calls in an Angular application is not recommended. Instead, utilize $http which ensures a digest cycle is triggered post-ajax call completion.
  2. If you absolutely need to use JQuery's AJAX, remember to use $apply after updating the scope.

Take a look at this updated plunker example demonstrating a more "angular" approach to handling AJAX requests.

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

Passing asynchronous data from method1 to method2 without impacting the functionality of the script responsible for fetching the asynchronous data in method1

When working with TypeScript, I encountered an issue while trying to invoke an external script called SPCalendarPro within a private method that asynchronously fetches data. The script is invoked in the following manner: private _getSPCalendarPro() { con ...

Guide on utilizing Json.net for extracting an array from a json document

After conducting thorough research, I have come across several solutions to similar problems like mine. Unfortunately, none of them have proven to be successful so far. My main goal is to parse a json file where the first item is an array structured like t ...

Selecting the events that I want my directives to track

Here is a directive example: 'use strict'; angular.module('epw') .directive('md-title', function ($rootScope) { return { scope: { listenTo: '@' }, controller: function () { $ ...

How can I create a script in Discord.js that automatically sends users their information upon joining the server?

I'm currently working on developing a code that automatically sends the user's avatar, username, ID, account creation date, server join date, and status when they join The structure of the code looks something like this: module.exports = (Discor ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

Running a Photoshop script that interfaces with the Google Apps Script REST API

I've been experimenting with integrating Photoshop and Google Apps Script API. I managed to create an API URL in Google Apps Script, but I'm facing issues with making requests and receiving results in my Photoshop Script. Here is the complete UR ...

Getting props value in parent component using Vue JS

In my development project, I am working with three key components: component-1, component-2, and an App component. Initially, I pass a Boolean prop from component-1 to component-2. Through the use of a @click event, I am able to toggle this prop value betw ...

Error in Node.js Socket.io: The disconnect event is being triggered before the connect event

When the client reconnects after a network drop, the disconnect event is triggered on the server. Client code: var url ='192.168.1.101', port = '80', socket = io.connect('http://' + url + ':' + port, { &apo ...

Exploring the possibilities of implementing the .map() function on a JSONArray within a ReactJS project using ES

When I receive a JSONArray from the server, my goal is to use .map() on it in order to extract key-value pairs of each object within the array. However, when I try to implement this code, I encounter an error stating "files.map is not a function". Can some ...

Require assistance in constructing a tree structure utilizing the jstree plugin and JSON within the MVC framework?

I am struggling to create a tree structure using the jstree plugin and Json within my MVC 4 project. However, there seems to be an error in my implementation that I can't seem to identify. Here is the Json snippet: [OutputCache(Duration = 0)] ...

Personalized HTML characteristics

Within the realm of AngularJS (and possibly jQuery UI), I've come across tags such as ui:some_random_name and ng:some_random_name. It seems that according to the HTML specification, non-standard attributes are not allowed. So how do these libraries m ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

The Javascript calculation function fails to execute proper calculations

I have been facing immense frustration while working on a project lately. The project involves creating a unique Webpage that can calculate the total cost for users based on their selections of radio buttons and check boxes. Assuming that all other functi ...

When iterating through a foreach loop in PHP, converting an array to a JSON object may pose a challenge

Having trouble converting an array in a foreach loop to the correct JSON object format for later parsing in C#. $data = []; $servers = $srv->getAllSrv(); foreach ($servers as $server) { $server->status(); $ip_port = $server->addr() ...

Receiving a 401 error while attempting to make an axios get request with authentication headers

I have been utilizing axios in my React project to fetch data from MongoDB. However, I am facing a challenge with the axios get requests returning a 401 error when I include my auth middleware as a parameter. This middleware mandates that the user must pos ...

Learn the process of transferring information from a dynamically generated table to a database using PHP

After creating a table using PHP dynamically, I am facing an issue with updating some cell values based on user input. I have provided my code below. I tried using [] in the names attribute to make names an array as suggested on Stack Overflow, but it didn ...

Struggling to find the element using Selenium

Hey there, I'm struggling with identifying the input id button in my HTML code while using Selenium through Java. The error message says it's unable to locate the element. Can anyone provide some guidance? I've already tried using xpath and ...

Retrieving the JSON data from an API using Laravel

Currently, I am experimenting with APIs and my latest project involves utilizing the Google Directions API within my application. To handle this, I have created a form to collect user input and generate the necessary URI directly in the routes.php file: ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...