Using AngularJS, trigger an httpget request when the value in a textbox is changed

I am currently working on a web service that returns a json file when called with an entry ID parameter. I have successfully created an Angular method to retrieve the data from this service. However, I am facing difficulty in recalling the service when the input ID changes. I want the method to be automatically triggered whenever a new value is provided.

The parameter I pass for the ID is named Reference. The current HTML code displays an object with a reference value of 1234. But if I try to change this value, I struggle to recall the service.

Below is my existing code:

Angular:

var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
    var res = $http({
        method: 'GET',
        url: 'AirPortrWebService.asmx/DashboardDetail',
        params: { Reference : '1234' }
    })
    .then(function (response) {
        $scope.booking = response.data
    });
    $scope.test = "Angular Method Called";
    $scope.Reference = '1234';

});

Html

<!DOCTYPE html>
<html>
<head>
    <script src="scripts/angular.js"></script>
    <script src="app/NewAppTwo.js"></script>
</head>
<body ng-app="myModule" ng-controller="myController">
    {{test}}
    {{Reference}}
    <br />
    <br />
    <input type="text" ng-model="Reference" ng-change="booking"/>

    {{booking}}
</body>
</html>

Answer №1

Implement a new function for ng-change="booking" that triggers whenever the Refences model is updated:

$scope.updateReference = function(referenceNumber){
  $http({
         method: 'GET',
         url: 'AirPortrWebService.asmx/DashboardDetail',
         params: { Reference :  referenceNumber}
  }).function (response) {
     $scope.booking = response.data
  });
}

<input type="text" ng-model="Reference" ng-change="updateReference(Reference)"/>

Answer №2

give this a shot:

let myApp = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
    $scope.refreshData = function(){
        let response = $http({
            method: 'GET',
            url: 'AirPortrWebService.asmx/DashboardDetail',
            params: { Reference : $scope.Reference }
        })
        .then(function (response) {
            $scope.bookingDetails = response.data
        });
    }
    $scope.message = "Method from Angular invoked";
    $scope.Reference = '1234';

});

and for the html code

<input type="text" ng-model="Reference" ng-change="refreshData()"/>

Using `ng-change` triggers the specified function each time there is an input change. The function `refreshData()` does not require any parameters as it utilizes `$scope.Reference`.

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

I am using a Next.js app where users can upload images through an API, and the API returns the images to me in an array. I am trying to figure out how

Instead of using CKEditor to upload images, I have implemented my own API for image uploading. When a user uploads an image on my website, I make a call to the API to safely upload the image and return a URL in the Public Domain. The API returns the follo ...

Having trouble with Gulp hanging on the task named 'some_task_name' when using gulp.parallel or gulp.series?

Out of the blue, my gulp configuration suddenly stopped working. It gets stuck on 'Starting...' when I use tasks with gulp.parallel or gulp.series. Just yesterday, the same config was running smoothly. Why did this sudden change occur? Here is a ...

NgModel in Angular Datapicker does not successfully transmit value

My page features a form that functions as a filter search, with one of the fields being a date field. I have configured the Angular UI datepicker plugin (https://github.com/angular-ui/ui-date) and the calendar pops up when I focus on the date field. Howe ...

How does Chrome have the capability to access the gist json file? Isn't that typically not allowed?

Fetching a JSON file from Github Gist can sometimes be straightforward, but in certain situations, I have faced difficulties due to CORS restrictions. This has led me to resort to using JSONP instead. Can you shed some light on why this is the case? ...

Searching for records within a text box can be easily done in AngularJS by triggering the enter button

When entering a record name in the text box of this code, I would like it to search for the record when I type and press the enter button. <input type="text" class="form-control" name="search" placeholder="Enter keyword to search" ng-model="Google" s ...

Easily transfer files from your browser application to your Windows applications such as Outlook or printer queues using a simple drag and

I am attempting to transfer a downloaded file from a web browser to a Windows application (such as Outlook or a printer queue) by dragging and dropping. While I can successfully drop the file onto the desktop or any other file explorer location, I face iss ...

Steps to deactivate a JavaScript function once the page has undergone a Page.IsPostBack event

My current setup involves a simple div with the display set to none. Upon page load, I use $("#MyDiv").show(); to display the div after a delay, allowing users to enter information into the form and submit it using an asp.net button. After submitting the ...

Creating a dynamic website with user-friendly editing capabilities

Having a good understanding of html5 and css3, I am currently exploring ways to create a website that enables visitors to edit content in real time for all other users to see. While aware of the contenteditable attribute, I have found that it does not reta ...

What is the most effective method for implementing the angular ng-app in your project?

As a beginner in Angular, I am wondering whether it is better to have one ng-app for the entire website or use multiple ng-app directives for individual pages? ...

The HTML slideshow is not automatically showing up as intended

I need to make a few adjustments to the picture slideshow on my website. Currently, all the pictures are displayed at once when you first visit the site, and it only turns into a slideshow when you click the scroll arrows. I want it to start as a slideshow ...

Enhanced Bootstrap Carousel with White Background Transitions

Having trouble articulating my issue, so here's a video that should clarify: https://example.com/video I'm using a bootstrap carousel template for a full-width slider. Despite my efforts to remove the white-space transitions, they persist. Am I ...

Resolving Angular ui-router, handling successful HTTP requests, and using state parameters are important

My objective is to: Firstly, insert a new record into the database using an HTTP POST request, resolve it with stateProvider, retrieve the new ID, and change the view and stateParams accordingly. This is the code for my HTTP POST service: myApp.service( ...

Cross-Origin Resource Sharing (CORS) in Ajax requests

I've been attempting to fetch variables from an external domain using AJAX and then populate pre-filled form fields with the retrieved data. However, I'm facing difficulties getting it to function properly. While I'm relatively new to JavaS ...

Express Power Tool - Error: app.set function is undefined

My journey with creating an API using Node/Express began with a solo endeavor to learn the basics in a 'naive' manner. The initial setup worked smoothly, prompting me to experiment with express-generator. Upon completion of the setup process, th ...

Guide on showcasing all entries in the database within the body section of an HTML table

Looking to showcase data from a table inside the body section of an html page This is the code I've been working on: <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="vi ...

Using VueJS to navigate to a specific route and pass parameters along with the

I'm a complete beginner when it comes to VueJS. Can someone please help me figure out how to access the deviceId in the Device component within vuejs? I've noticed that the deviceId in the h1 tag is not displaying on the Device component page. ...

Creating mesmerizing noise animation using THREE.FilmPass() in Three.js

Chapter Eleven of my Learning Three.js book showcases a fascinating noise animation created by the author using var effectFilm = new THREE.FilmPass(0.8, 0.325, 256, false); In the code example from the book, it is interesting to note that removing the orb ...

What is the importance of including parentheses when passing a function to a directive?

Hello, I'm currently a beginner in Angular and I am experimenting with directives. Here is the code snippet that I am using: HTML <div ng-app="scopetest" ng-controller="controller"> <div phone action="callhome()"> </div> </div ...

In Firefox, the HTML label fails to activate the corresponding input field when the mouse is moved while clicking

If you click on the label in the example below, it will change the state of the input. document.querySelector("label").addEventListener("click", function() { console.log("clicked label"); }); label { -webkit-user-select: none; -moz-user-select: no ...

The functionality of res.send is not working correctly

Attempting to send a response from my express application to the front-end in order to display an alert. Here is what I have attempted in my app: if (info.messageId) { res.redirect('back'); res.send({ success: true }); } ...