`AngularJS's approach to two-way data binding`

As I develop a web application using AngularJS, I have a button that triggers a call to a web service.

 [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public void retrieveRecord(string id)
    {
        List<object> records = new List<object>();
        SqlCommand cmd = new SqlCommand("select * from erp_admin.CompanySonVinUnitVenueRpt where comsonvinid in (select id from companysonvinunitvenue where id='"+id+"')",con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while(dr.Read())
        {
            records.Add(new
            {
                attendee1 = dr["comattendee1"].ToString(),
                attendee2 = dr["comattendee2"].ToString(),
                totalmale = dr["attendeetotalmale"].ToString(),
                totalfemale = dr["attendeetotalfemale"].ToString(),
                unit1 = dr["unitattendee1"].ToString(),
                unitd1 = dr["unitattendee1desig"].ToString(),
                unit2 = dr["unitattendee2"].ToString(),
                unitd2 = dr["unitattendee2desig"].ToString(),
                unit3 = dr["unitattendee3"].ToString(),
                unitd3 = dr["unitattendee3desig"].ToString(),
                unit4 = dr["unitattendee4"].ToString(),
                unitd4 = dr["unitattendee4desig"].ToString(),
                unit5 = dr["unitattendee5"].ToString(),
                unitd5 = dr["unitattendee5desig"].ToString(),
                remarks = dr["remarks"].ToString()
            });
        }
        con.Close();
        var json = js.Serialize(records);
        Context.Response.Write("{" + '"' + "records" + '"' + ":" + json + "}");
    }

The above webservice has been successfully tested and is functioning properly. This part of the code resides in my AngularJS file:

                 $scope.updatefunction = function (param) {
                        $http.get('/frmattendencerptqed.asmx/retrieveRecord', {
                            params: {
                                id: $scope.updateparam.comsonvinid
                            }
                        })
                        .then()
                        {

                        }
                    }

This snippet represents my AngularJS code

Additionally, this code represents my input field

<input type="text" ng-model="remarks" style="width:100%;" />

Currently, I am looking to retrieve the previous value from the database and populate the textbox with this value. If the user makes changes in the textbox, I want the value to be updated on button click.

How should I proceed with this implementation?

Answer №1

This is the designated input field

<input type="text" ng-model="remarks" style="width:100%;" />

Now I must retrieve the previous value from the database and bind it to the textbox. If the user makes edits to the textbox, the value should only update upon button click.

Which specific remarks property are you referring to? Your webservice returns a JSON object containing an array of structured objects, each potentially containing a remark property.
Can you please provide the JSON result of the webservice call for more clarity?

Regarding how to retrieve and bind the data in your AngularJS controller, here is a solution:
Refer to https://docs.angularjs.org/api/ng/service/$http to access the response data property in the returned object.

data – {string|Object} – The response body transformed using the transform functions.

You can implement the following approach:

$scope.updatefunction = function (param) {
                        $http.get('/frmattendencerptqed.asmx/getuprec', {
                            params: {
                                id: $scope.updateparam.comsonvinid
                            }
                        })
                        .then(                  
                                   // handle success
                                function(response){
                                 $scope.remarks=response.data.selectrecd[indexYourWish].remarks 
                                },

                                function(errResponse){  
                                   // handle error
                                    return $q.reject(errResponse);
                                }
                             );                                
                    }

As mentioned earlier, I am referencing an array to fetch the information in response.data with an index that you need to define. If you are not working with an array, consider not using an index at all.

remarks should be a variable within the scope of your controller. The syntax for your controller may vary depending on your AngularJS setup (I personally avoid using $scope.xxx syntax).
For a more detailed answer, please provide additional snippets of your JS code.

Answer №2

This is how the typical behavior of angularjs functions. For a detailed explanation, you can refer to this tutorial:
http://www.w3schools.com/angular/angular_databinding.asp It is important to note that all you have to do is call the update function from your controller and provide the variable you want to bind to the input field.
This variable can be assigned to either $scope or to this in the controller (both methods are acceptable).

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

Retrieve specialized information from a json file

I have a JSON variable called json which contains some data in JSON format. I am attempting to extract a specific portion of that data. One way to do this is by using the index as demonstrated below: var newdata = json[listid].Taxonomies[0]; However, my ...

Angular's Conditional ng-if Error

Encountering an error link from Angular Js [1]http://errors.angularjs.org/1.2.10/$parse/lexerr?p0=Unterminated%20quote&p1=s%2013-14%20%5B'%5D&p2=recipe.ID%20!%3D%3D' I am struggling to implement the solution for this error. Any help wou ...

Exploring the power of recursive Angular directives

Recursion in angular directives is necessary for creating a left menu. The code provided without recursion does not achieve the desired menu structure. Implementing recursion is key to generating the left menu recursively. Uncertain about the recursion ...

Calculating the Quantity of Specific Nodes within a JSON Dataset using AngularJS

Here is a collection of JSON data: "MyMessages": [ { "Code" : "N101", "ID" : "History", "Indicator" : "Down", "PosChangeMessage" : "test test test test", "NegReasonMessage" : "test test ...

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

Showcasing a graphical representation with the help of Highcharts

I am currently exploring JavaScript and trying to familiarize myself with interactive charts using the HighCharts library. Unfortunately, I have been facing some challenges in getting the graph to print correctly. Despite attempting various examples, none ...

Locate and eliminate all occurrences of "<br />" within a webpage using jQuery

I am currently working on a project using the Cargo Collective platform and I have noticed that it automatically includes unnecessary <br /> tags in the body of my document. Is there a way to use jQuery to scan for all instances of <br /> tags ...

Upon refreshing the page, an inline script was not executed due to its violation of the Content Security Policy directive: "script-src 'self'"

When I refresh the page on my production build for all routes except "/", I encounter an error in my Node/React app which results in a blank page being displayed. The error message states: "Refused to execute inline script because it violates the followi ...

What is the best way to create an arrow that tracks the browser window, but only goes as far as the end of its designated container

Currently, I am facing a challenge in implementing a scroll down arrow. While this is typically a simple task, it has proven to be a bit more complex this time around. The complexity arises from the fact that my customer desires a homepage with an image of ...

A guide on incorporating multiple nested loops within a single table using Vue.js

Is it possible to loop through a multi-nested object collection while still displaying it in the same table? <table v-for="d in transaction.documents"> <tbody> <tr> <th>Document ID:</th> &l ...

Tips for embedding Javascript code within the window.write() function

I have a JavaScript function that opens a new window to display an image specified in the data variable. I want the new window to close when the user clicks anywhere on it. I've tried inserting some JavaScript code within window.write() but it doesn&a ...

Why is the ajax request in JQuery initiated before the code in beforeSend is fully executed?

I have encountered an issue with my code. I am trying to get a Reload.gif to start playing on my webpage before sending an ajax request to reload the data. However, the GIF only starts playing after the success function is called. Here is the timeline of e ...

Developing a Rails application integrated with Pusher or Faye for real

I've been tasked with creating an app similar to this: I'm facing challenges in updating the bids. I am considering using technologies like Pusher or Faye ( or ) and subscribing to each event. However, I'm wondering if there is a more elega ...

Enhancing features with jQuery's .animate() function

Can anyone help me figure out why the div on the right is not pushing itself away from the one on the left when I hover over it? I want it to move on mouseenter and return to its original position on mouseleave. The changing background colors are just ther ...

Developing a innovative and interactive nested slider using Jssor technology

Trying to implement a dynamic jssor nested slider to showcase albums and images from a mySQL database. Everything works fine with a single album, but when there are two or more albums, the display gets messed up. I'm still learning JavaScript and JQue ...

Unable to POST data from Angular.js to Express.js

I'm facing issues with the communication between my Angular.js application and my Express.js REST API. I am using Yeoman 1.0 along with generator-angular 0.7.1. I attempted to use a middleware configuration for my grunt serve, but I could not get it ...

Separating a variable within a Twitch bot: techniques and tips

I am working on setting up a feature in my Twitch bot where it can respond to the command !test [var]. For example, if someone types !test @jeff, the bot would reply with hello @jeff. Currently, I am using tmi. client.on('chat', function(channe ...

How to remove outer quotes from JSON data in Reactjs after using JSON.stringify

When using JSON.stringify on a Json data, I noticed that the resulting string includes double quotes at the beginning and end. For example: x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}} After using JSON.stringify, the result looks like t ...

The latest pathway fails to refresh in NextJs

I've implemented a search bar at the top of my app which directs to /search/[searchId].js page: <Link href={`/search/${search}`}> <button type='submit' className='btn-cta btn-3'>SEARCH</button> < ...

Streamline the process of renaming or remapping keys in a collection of JavaScript/JSON objects

Structured JSON data is essential. Imagine using JSON.parse(): [ { "title": "pineapple", "uid": "ab982d34c98f" }, { "title": "carrots", "uid": "6f12e6ba45ec" } ] The goal is to transform it by changing titl ...