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: https://i.sstatic.net/mGUVN.png

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

Utilizing Google Language API for bulk translation tasks

My current project involves using Google's AJAX Language API to translate each element in an array. for(var i=0; i < mytext.length; i++) { google.language.translate(mytext[i], originalLanguage, newLanguage, function(result){ if(!result.error){ ...

Allowing unauthorized cross-origin requests to reach the SailsJS controller despite implementing CORS restrictions

My cors.js file has the following configuration: module.exports.cors = { allRoutes: true, origin: require('./local.js').hosts, // which is 'http://localhost' } I decided to test it by making a request from a random site, Here is ...

How about starting a Node.js application with specific configurations?

Is there a way to develop a Node.js app that can be initiated with additional parameters? Here are a few examples: node myApp.js -nolog This command would initialize the app with the custom parameter noLog=true, preventing console logging. node myApp.js ...

Incorporating custom HTML5 player to watch Youtube videos on my website

I'm trying to display YouTube videos on my website using a simple video tag. I've managed to retrieve the encoded url of the video from the page source and successfully download it through IDM, but when I try to use this URL as the source for an ...

The Angular method for retrieving the child's ID when it is clicked

As a newcomer to Angular 1.0 with a background in jQuery, I am facing the following scenario: Let's imagine we have the following HTML structure : <div id="filters"> <div id="filter1">Filter 1</div> <div id="filter2"> ...

The AutoComplete feature of MaterialUI Component fails to function properly even when there is available data

I am facing an issue with my component as it is not displaying the autosuggestions correctly. Despite having data available and passing it to the component through the suggestions prop while utilizing the Material UI AutoComplete component feature here, I ...

Tips for invoking a function with dependencies in an external library

Recently diving into the world of Angular, I've encountered a challenge. I'm struggling to find a way to call a function on a provider that I have created from within a section of code executed under the context of an external component. The main ...

Add United States as an additional attribute to the countries retrieved from the API

I am working with an API that provides data in a specific format: [ { "id": 12, "acf": { "address": { "city": "Bandar Penawar", "state": "Johor", "country ...

Utilizing 2 Controllers and 1 Value with AngularJS

Exploring the realm of global variables while honing my skills in AngularJS's factory and service functionality led me to encounter a perplexing error. The issue arises when two controllers attempt to share a global variable, triggering the following ...

I have difficulty generating appropriate pseudonyms

Struggling to create aliases in my react project (CRA 3.1.1) has been a challenge for me. Despite attempting various methods, I have not been successful in achieving it. The only success I've had so far is aliasing the simple "src" folder based on som ...

Broadcast to every socket except the one that is malfunctioning on Socket.io

My current task involves sending a message to all connected sockets on my server using socket.io. The code I have written so far looks like this: if(electionExists) { var connectedClients = io.sockets.adapter.rooms[electionRequested].sockets; ...

Understanding the npm install command

I'm trying to understand how npm install actually functions. Shouldn't it have automatically installed all the dependencies listed in package.json? I visited the documentation npm install npm install (in package directory, no arguments): ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

The script is not functioning properly due to an error stating "(Uncaught ReferenceError: $ajaxUtils is not defined)"

I'm having trouble figuring out what the issue is (Uncaught ReferenceError: $ajaxUtils is not defined) document.addEventListener("DOMContentLoaded", function (event) { showLoading("#main-content"); $ajaxUtils.sendGetReque ...

Attempting to decode the string prior to selecting an item from the Vue.js/Nuxt array

Hey there, I really appreciate anyone who can assist me with this. I've been dabbling in Laravel for a few months and now I'm trying to dive into studying Nuxt. The specific type of translation I need help with is proving to be quite challenging ...

Dispatch keystrokes to a designated text field if they are not taken in by any other input

Is there a way to achieve the functionality seen in apps like Discord, where users can type into the message box even when it's not in focus? I am interested in implementing this feature only if no other input field on the page is currently focused. ...

Passing data from React component to JavaScript page or function

I am trying to pass a variable called "pokemon" from Cell.js to Detail.js. Cell.js creates buttons, each representing a different pokemon. When clicked, it should navigate to a detailed page about the specific pokemon. Therefore, I need to send the pokemo ...

Encountering an error while attempting to merge webgl_interactive_cubes with pointer lock in three.js: "Unable to access properties of undefined (reading 'getHex')."

I’m in the process of developing a scene with walk-navigation and interactive objects for educational purposes. To achieve this, I am utilizing the Pointer Lock Control example for walk navigation and the interactive cubes example from three.js. The proj ...

The issue arises when using IE8/9 with $.get and .html() functions, as the retrieved data

Below is a snippet of JavaScript code that I am currently working with: $(".refresh").on("click touch", function () { $.get($("a.suggest-date").attr('href') + '#suggestedDate', null, function (result) { console.log(result); ...

Picture in a clear background without any alteration

Is there a way to create a background-color with opacity inside an image without affecting the image itself? The issue lies in the fact that the transparent background-color makes everything underneath it, including text and the image, transparent. Below ...