Difficulty encountered while connecting JSON data to a list using Angular JS

Currently, I am working on developing an application using AngularJS. In this project, I need to populate the customer list using data from a database. To achieve this, I have written a web method to retrieve the necessary data:

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string getname()
    {
        SqlHelper sql = new SqlHelper();

        DataTable dt = sql.ExecuteSelectCommand("select cust_F_name,cust_L_name from customer");

        Dictionary<string, object> dict = new Dictionary<string, object>();
        object[] arr = new object[dt.Rows.Count];
        List<CustName> custName = new List<CustName>();
        
        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            CustName c = new CustName();
            c.cust_F_name = dt.Rows[i]["cust_F_name"].ToString();
            custName.Add(c);
        }
        
        dict.Add("JsonCustomer", custName);
        
        JavaScriptSerializer json = new JavaScriptSerializer();
        return json.Serialize(dict);
    }

}
public class CustName
{
    public string cust_F_name { get; set; }
}

To fetch the JSON data, use the following code:

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

DemoApp.factory('SimpleFactory', function ($http) {
    return {
        getCustomer: function () {
            return $http.post('Home.aspx/getname', { name: "" });
        }
    };
});

DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
    SimpleFactory.getCustomer().then(function (customer) {
        $scope.Customer = customer.data;
    }, function (error) {
        // error handling
    });
});

To display the data, use the following HTML:

<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="DemoApp">
<head runat="server">
    <title></title>
</head>
<body data-ng-controller="SimpleController">
    <form id="form1" runat="server">
    <div>
        Name<input type="text" data-ng-model="Name" />{{ Name }}
        <ul>
            <li data-ng-repeat="customerName in Customer | filter:Name">{{ customerName }} </li>
        </ul>
    </div>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="Script/Home.js" type="text/javascript"></script>
</body>
</html>

Currently, the output I am receiving is:

However, I would like to access the data in JSON format in name-value pairs. I'm unsure how to accomplish this and would appreciate any guidance you can provide. Thank you in advance.

Answer №1

When receiving results in the form of a JSON string, it is important to convert it into a JavaScript object using the angular.fromJson method.

For instance:

DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customerData) {
    var customersRawObject = angular.fromJson(customerData);
}, function (error) {
    // handle errors
});})

Following that, you can proceed to do something like this:

$scope.customerA = customersRawObject.JsonCustomer[0];

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

Warning: Promise rejection not handled in error

I've been working with nodejs, express, and argon2 in my project. However, I encountered an error that has left me puzzled as to why it's happening. Strangely, even though I don't have any callbacks in my code, this error keeps popping up. H ...

The issue with Express connect-flash only showing after a page refresh instead of instantly displaying on the same page needs to be addressed

Here is the registration route code snippet: router.post("/register", function(req, res){ var newUser = new User({username: req.body.username}); User.register(newUser, req.body.password, function(error, user){ if(error){ req.fl ...

Building a versatile memoization function in JavaScript to cater to the needs of various users

There is a function in my code that calculates bounds: function Canvas() { this.resize = (e) => { this.width = e.width; this.height = e.height; } this.responsiveBounds = (f) => { let cached; return () => { if (!cache ...

Utilizing Material UI's TextField components for validating React forms

I've spent the past hour researching this topic and unfortunately, there isn't much information available on the internet. My goal is to validate input fields to ensure that all fields are filled out; otherwise, an error will be displayed. The le ...

The communication breakdown between Jquery and PHP caused a malfunction

Apologies for the questions, but I am stuck on this minor issue. Being a rookie has its effects :) I have a JSON format representing a list of games with rounds and player information for each round. In this example, only 1 game with 3 rounds is shown: { ...

Leveraging the power of JavaScript and possibly regular expressions to extract numerical values from a

I am attempting to extract a variable number from the text provided in the following example: Buy 5 for € 16.00 each and save 11% Buy 50 for € 15.00 each and save 17% Buy 120 for € 13.00 each and save 28% Buy 1000 for € 10.00 each and save 45% Th ...

Once the Ajax request is finished, the cookie deletion function ceases to function

When the website loads, a cookie is generated using PHP before any other content or headers are sent. This is done with the following code: $steam_login_verify = SteamSignIn::validate(); if(isset($_COOKIE['userid'])) { //work with cookie va ...

Aligning divs, prevent duplicate HTML within multiple divs

Currently, I am attempting to troubleshoot a jsfiddle issue. The main problem lies in my desire for the first two divs (with class="fbox") to be aligned next to each other on the same level. Furthermore, I am looking to enable dragging the image into the ...

Utilizing Datatables with mysqli for server-side processing through JSON

I'm encountering an issue with my implementation of datatables. Certain pages are crashing due to the large amount of data being fetched from the database. I attempted to resolve this by utilizing server-side processing. Despite following the examples ...

Steps to keep only one submenu open at a time and close others

Struggling to figure out how to open one submenu at a time, and I can't seem to locate the issue! I've searched around for solutions but haven't found anything that works for me. The submenu also needs to remain closed when the page loads. - ...

Mongodb failing to recognize the concat function

I have a field within my collection that looks like this: uniqueId: 123 inTarefa: true exclude: "ab,cd," orderId: 987 I am attempting to update all of the values using a "FindOneAndUpdate" query like so: collection.findOneAndUpdate({ 'uniqu ...

The error message SCRIPT1003 is indicating that a colon was expected

There are many questions with this title, but I have a unique one for you. An error message "SCRIPT1003: Expected ':' (1,78)" pops up when I launch my website. I am using webpack and typescript in my project. Below is my tsconfig: { "co ...

Exploring the issue: Why is data being submitted when cancelling an AngularJS and Bootstrap modal form?

Encountering an issue with AngularJS and Bootstrap UI in a modal Form where the form submission is triggered on cancel. Check out my Plunker for a demo of the problem. Upon cancellation, an Alert pops up during submission which should not occur. What am I ...

How can I effectively display the names of the months in AngularJS?

When working on an Angularjs project, what is the most efficient way to include the titles of the months in HTML? Here is a snippet of my current hard-coded solution that I am looking to improve: <div> <div class="col-xs-3"> <d ...

Guide on using JavaScript to implement the universal CSS selector

One technique I frequently employ is using the CSS universal selector to reset the dimensions in my HTML document: * { border: 0; margin: 0; padding: 0; } I wonder if a similar approach can be achieved with JavaScript as well? When it come ...

What is the method to eliminate waitedMS and ok values from the output of a MongoDB aggregation query?

I have a MongoDB PHP application where I am using aggregation commands. Here is the code snippet: <?php $query = array('$or' => array( array('employeeList'=>array('$exists' => false)), array('emplo ...

What is the best way to delay a recursive JavaScript function for 3 seconds?

Before writing this post, I have already come across the following questions: how-to-pause-a-settimeout-call how-to-pause-a-settimeout-function how-to-pause-a-function-in-javascript delay-running-a-function-for-3-seconds Question The below code snipp ...

Sending an AJAX request from one subdomain to another subdomain within the same domain

Is it true that cross-domain ajax requests require a 'proxy' server to be used? But what if an ajax request is made from server1.example.com to server2.example within the same domain of example.com? Would that still not work? I've noticed ...

How to dynamically change the color of an AngularJS element based on a condition?

As someone who is new to AngularJS, I am currently working on changing the color of a table element to yellow if the user has voted on a specific choice. <div ng-show="poll.userVoted"> <table class="result-table"> <t ...

Position a dynamic <div> in the center of the screen

My goal is to design a gallery page with a list of thumbnails, where clicking on a thumbnail will open the related image in a popup div showing its full size. The issue I'm facing is how to center the popup div on the screen, especially when each pic ...