Troubleshooting: Why Your Angular Data Binding is Failing

I am integrating a WCF REST service with an AngularJS application. My goal is to retrieve account information based on the account number provided, however, I am encountering an issue where the text "Account_Type" is displayed three times before showing the actual values.

Below is the code snippet for the method:


  public string AccountDetails(string Account_Number)
        {
            var accountNumber = int.Parse(Account_Number);//It could be better to use TryParse
            using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
            {
                var inOut = context.Current_Account_Deposit.Where(x => x.Account_Number == accountNumber).Select(w => new AccountTransaction
                {
                    Account_Number = w.Account_Number,
                    Account_Balance = (decimal?)0M,
                    Deposit = (decimal?)w.Amount,
                    Withdrawal = (decimal?)null,
                    Date = w.Date,
                     Account_Type=null,  
                    Account_Holder_Tittle = null,
                    Account_Holder_FirstName =null,
                    Account_Holder_LastName = null
                }).Union(context.Current_Account_Withdraw.Where(x => x.Account_Number == accountNumber).Select(d => new AccountTransaction
                {
                    Account_Number = d.Account_Number,
                    Account_Balance = (decimal?)0M,
                    Deposit = (decimal?)null,
                    Withdrawal = (decimal?)d.Amount,
                    Date = d.Date,
                    Account_Type = null,
                    Account_Holder_Tittle = null,
                    Account_Holder_FirstName = null,
                    Account_Holder_LastName = null
                })).OrderBy(r => r.Date)
                .Union(context.Current_Account_Details.Where(x => x.Account_Number == accountNumber).Select(e => new AccountTransaction
                {
                    Account_Number = e.Account_Number,
                    Account_Balance = (decimal?)e.Account_Balance,
                    Deposit = (decimal?)0M,
                    Withdrawal = (decimal?)0M,
                    Date = e.Account_Creation_Date,
                    Account_Type=e.Account_Type,  
                    Account_Holder_Tittle = null,
                    Account_Holder_FirstName =null,
                    Account_Holder_LastName = null

                }))
                .Union(context.Current_Account_Holder_Details.Where(x=>x.Account_Number ==accountNumber).Select(d=> new AccountTransaction
                {
                    Account_Number = d.Account_Number,
                    Account_Balance = null,
                    Deposit =null,
                    Withdrawal = null,
                    Date = null,
                    Account_Type = null,
                    Account_Holder_Tittle =d.Tittle,
                    Account_Holder_FirstName=d.Account_Holder_First_Name,
                    Account_Holder_LastName=d.Account_Holder_Last_Name


                }));
                var js = new System.Web.Script.Serialization.JavaScriptSerializer();
                return js.Serialize(inOut);
            }
        }

Below is the accompanying code:

@{
    Layout = null;
}

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http, $window) {
            $scope.IsVisible = false;
            $scope.Search = function () {
                var post = $http({
                    method: "GET",
                    url: "http://localhost:52098/HalifaxIISService.svc/AccountDetails/" + encodeURIComponent($scope.Account_Number),
                    dataType: 'json',
                    headers: {
                        'Accept': 'application/json, text/javascript, */*; q=0.01',
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                });

                post.then(function (response) { // .success(function(data => .then(function(response
                    var data = response.data; // extract data from resposne
                    $scope.Customers = JSON.parse(data); // eval(data.d) => JSON.parse(data)
                    $scope.IsVisible = true;
                }, function (err) {
                    $window.alert(err);
                });

            }
            $scope.grandTotal = function () {
                return $scope.Customers.reduce(function (previousTotal, m) {
                    var valueToAdd = parseFloat(m.Deposit);
                    if (isNaN(valueToAdd))
                        return previousTotal;
                    return previousTotal + valueToAdd;
                }, 0); // Send in 0 as the default previousTotal
            }
            $scope.grandTotal1 = function () {
                return $scope.Customers.reduce(function (previousTotal, m) {
                    var valueToAdd = parseFloat(m.Withdrawal);
                    if (isNaN(valueToAdd))
                        return previousTotal;
                    return previousTotal + valueToAdd;
                }, 0); // Send in 0 as the default previousTotal
            }

        });
    </script>


    <div ng-app="MyApp" ng-controller="MyController">
        Account Number:
        <input type="text" ng-model="Account_Number" />
        <input type="button" value="Submit" ng-click="Search()" />
        <hr />
        <br />         


        <div ng-repeat="m in Customers" ng-show="IsVisible">Account Type:{{m.Account_Type}}</div>       



    </div>
</body>
</html>

This screenshot displays the output of running the application:

Answer №1

To retrieve the Account_Type data, there is no requirement for using an ng-repeat in this scenario. Simply assign the value to the $scope variable.

 $scope.Account_Type = details[0].Account_Type;

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

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

What could be causing the input event not to be triggered consistently when I select or highlight text?

I have implemented a 4-digit pin field with a specific behavior: when a field is filled, the focus automatically shifts to the next field (the cursor moves to the next input field). If text in a field is deleted, the text in that field is also removed and ...

What is the best way to showcase navigation and footer on every page using AngularJS?

I'm in the process of building a Single Page Application. I've decided to create separate components for Navigation, Section, and Footer. The Navigation and Footer should be displayed on every page, while only the Section content changes when nav ...

Error: Unable to access the 'resource' property as it is undefined

I am currently working on a project that involves fetching the latest 4 results from Craigslist using a query. Although I have successfully retrieved all the relevant information, I seem to be encountering an issue with loading the URL of the image from th ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Analyzing the functionality of Express with Mocha and Chai

Currently facing an issue with testing my express server where I am anticipating a 200 response. However, upon running the test, an error occurs: Test server status 1) server should return 200 0 passing (260ms) 1 failing 1) Test server statu ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

Printing dynamic data

When the print button is clicked, I need to print dynamically generated data from a table that has an ID. The table data (td and tr) is dynamically generated. I have successfully retrieved the table data and attempted to print everything using window.prin ...

Using the window.prompt function to send information to specific fields in a MySQL database is not functioning correctly. I am looking for assistance with this issue

Currently, I am attempting to send some data to a server that is MySQL-based. After running the code below, it seems like there are no errors showing up in the console. Can you please review this code and let me know if you spot any issues? I would really ...

How to retrieve multiple checked values from checkboxes in Semantic UI React

Trying to enable users to select multiple checkboxes in react using semantic-ui-react. I am new to react. Here is my code: class ListHandOver extends React.Component { state = { data: {} } handleChange = (e, data) => { console.log( ...

After submitting my form, the Bootstrap Modal does not hide as intended by my Ajax

I am facing an issue with my webpage that displays 6 Bootstrap Cards in 3 columns. Each card contains an image, name, description, and a footer button. When a user clicks on the button, a Bootstrap Modal opens with specific data fetched from a SQL row by I ...

Requires a minimum of two page refreshes to successfully load

Our website is currently hosted on Firebase. However, there seems to be an issue as we have to refresh the website at least twice in order for it to load when visiting www.website.com. Update: We are unsure of what could be causing this problem. W ...

How to disable annoying browser ad extensions using Javascript

Is there a way to prevent browser add-ons from injecting HTML code? My website built in angularjs is experiencing routing issues due to certain browser add-ons. The following HTML snippet is causing errors in my angularjs: <script async="" src="http:/ ...

Adjust the formatDate function in the Material UI datepicker

I recently implemented the material-ui datepicker component with redux form and it's been working great. However, I have encountered a minor issue. Whenever I change the date, it displays in the input field as yyyy-mm-dd format. I would like it to app ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

What steps can I take in JavaScript to assign a value of 0 to values[1] in order to prevent receiving NaN as the output

I'm currently working on a program that calculates the sum of 6 input values, but I've encountered an issue where if a value is missing (for example, only providing 5 values), the result becomes NaN. I attempted to address this by assigning empty ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...