What is the best way to extract user input and pass it to an AJAX request URL?

Recently, I successfully completed an AJAX request using AngularJS. You can check out the code here.

Everything was working perfectly until I tried to add a dynamic variable (city) to the link like this:

$http.get('http://api.wunderground.com/api/KEY/forecast/geolookup/conditions/q/San_Francisco.json')
. Once I added the variable and tried to submit it after assigning it to ng-model="city", I encountered the following error:

"city is not defined"

I am looking for a solution that allows me to fetch the city name from the input field and use it in my newAJAXreq function when the "Find Weather" button is clicked. Additionally, I would like the default link to remain static for first-time visitors, but dynamically update based on user input afterwards. Your suggestions would be greatly appreciated. Thank you!

Answer №1

Your approach has a few issues that need to be addressed.

  1. It's recommended not to name your controller. Instead, use an anonymous function that takes the necessary modules as parameters, like
    .controller(function($http){ //do something });
    or
    .controller(['$http',function($http){ //do something }])
    . This helps in avoiding variable reference loss when minifying your JS files.
  2. Within your controller, define the desired function with the required parameter, such as
    $scope.sendAjax = function(city){ //do something }
    . From your view, you can call this function with just the argument needed, like
    ng-submit="sendAjax(city)"
  3. Try to minimize the use of scope. As mentioned in the book AngularJS: Up and Running by Shyam Seshadri and Brad Green:

Prior to 1.2 version of AngularJS, $scope was injected into the controller, and variables like helloMsg and goodbyeMsg were set on it. But starting from AngularJS 1.2, there is a new syntax known as the controllerAs syntax which allows defining variables on the controller instance using the this keyword, and accessing them through the controller from HTML.

The advantage of this syntax over the older one is that it clearly indicates in the HTML which variable or function belongs to which controller and its instance. It eliminates the need to search for variables within the codebase, especially in complex, nested UIs. The controller instance is directly identifiable in the HTML.

To implement this, utilize the controller as syntax in your view:

"ng-controller="WeatherController as weather"
, then always refer to the alias to access Weather Controller scope, like
ng-submit="weather.sendAjax()"
.

In your controller, assign the function to this, for example

this.sendAjax = function(){ \\do something }
. It's good practice to assign this to another variable to avoid it being overridden. You can initialize a variable as self in the beginning of your controller script like var self=this and continue referencing the controller as self onwards, e.g.,
self.sendAjax = function(){ \\do something }

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

Updating the contents of one specific div without affecting all other divs with the same class

Below is the HTML code snippet in question: <a class="btn test-btn test-btn-1"> <span>Content 1</span> </a> This particular code block appears multiple times on the page. The number at the end of test-btn- is dynamically generat ...

Ways to retrieve text from an input field using Protractor

Looking through the protractor documentation, I came across an interesting example: describe('by model', function() { it('should find an element by text input model', function() { var username = element(by.model('username&ap ...

Exploring the contrast between 'completed' and 'upcoming' in callback functions within node.js

Within the passport documentation for authentication configuration, there is a function that appears rather intimidating as it utilizes the enigmatic function "done." passport.use(new LocalStrategy( function(username, password, done) { User.findOne( ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...

Puppeteer has a limit of running only three instances on Heroku

Currently, I am in the process of developing a website that employs puppeteer to extract information from another site. The npm server works flawlessly on my local machine, but once deployed on Heroku, it halts after processing the first three files. The ...

Creating a React render method that relies on both asynchronous requests and state changes

Currently, I am immersing myself in the world of ReactJS and Redux. However, I have encountered a hurdle that seems insurmountable to me. In one of my projects, I have a React component that is responsible for fetching data asynchronously. export class M ...

Learn the process of extracting data from dynamically generated elements in JavaScript

I am a beginner in Javascript and Jquery and have recently started exploring business rules with Chris Powers. https://github.com/chrisjpowers/business-rules My current project involves adding a range slider for numbers and a number spinner. I attempted us ...

Clicking to close tabs

I am currently working on implementing a tab functionality on my website and I want these tabs to be responsive. Here is the code snippet I have been using: function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.ge ...

How can I securely store passwords for web scraping with Puppeteer to ensure maximum safety?

Looking for advice on scraping a website that requires login. The current code saves username and password in a config JSON file, which poses a security risk if the file is accessed by unauthorized individuals. Is there a more secure method, such as encr ...

Error encountered while executing the yarn install command: ENOTFOUND on registry.yarnpkg.com

Typically, when I execute the yarn install command, it goes smoothly without any complications. However, lately, when using the same command, I am encountering the following error: An unexpected error occurred: "https://registry.yarnpkg.com/@babel/core/- ...

Issue with form validation encountered while utilizing the ion-scroll element

I am currently facing challenges with form validation in my Ionic app when using the < ion-scroll> tag. Here is an example of my form: <form ng-show="!success" name="form" role="form" novalidate ng-submit="register()" show-validation> < ...

Nodejs and Express are seamlessly integrating error handling with database submission, ensuring a smooth flow of data processing

While testing my backend using nodejs and express, I encountered an issue with error handling in postman. The error message displays correctly for the 'Multiplier' column validation, but despite this, the data is being submitted into my mysql wor ...

Having difficulty locating local grunt while trying to use grung ngtemplates

After following the setup instructions for grunt angular templates from here I proceeded with installing grunt-angular-template by running this command: npm install grunt-angular-templates --save-dev The installation was successful. My package.json fil ...

Animating Angular for particular conditions

My goal is to create unique animations for specific state changes in my AngularJS app. I found inspiration from this tutorial: https://scotch.io/tutorials/animating-angularjs-apps-ngview, which works well. However, I am aiming for the following animations: ...

What is the best way to choose the initial p tag from an HTML document encoded as a string?

When retrieving data from a headless CMS, the content is often returned as a string format like this: <div> <p>1st p tag</p> <p>2nd p tag</p> </div> To target and select the first paragraph tag (p), you can extract ...

Collaborative real-time text editing tool for Angular on ASP.NET with multi-user functionality, powered by

I'm interested in integrating support for multiple contributors similar to Google Docs into my AngularJS 1.x application which has an ASP.NET MVC backend. Considering how SignalR is becoming outdated and with Office Online enabling real-time collabora ...

AngularJS: unique custom directive for bi-directional binding

I am facing a challenge where I need to create a directive with specific behavior: Controller: vm.mymodel = 'Hello World' Html: <custom-input mydirective="{propbind: 'data-value', propmodel: vm.mymodel}"></custom-input> ...

In what way can I modify the object in the first array when the second array includes the same object but with varying values, excluding the primary value?

This is the initial array I am working with [{"e":"24hrTicker","E":1532084622977,"s":"ETHBTC","p":"-0.00260600","P":"-4.029","w":"0.06279622", "x":"0.06465200","c":"0.06207700","Q":"0.10800000","b":"0.06207900","B":"0.58000000","a":"0.06209300", "A":" ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Display or conceal various objects using a single button in HTML

I've been working on creating a chatbot widget for my website, but I've run into an issue. The "Chat with us" button only shows the bot and not the close button as well. Here's what I've attempted: <input id="chat" type="button" on ...