Exploring AngularJS: Extracting Data Using the GET Method

Here is my Controller:

angular.module('apartmentCtrl', [])

.controller('ApartmentController', function ($scope, $http, Apartment) {
    $scope.loading = true;

    $scope.myLocation = '';

    Apartment.get($scope.myLocation).success(function (data) {
        $scope.apartments = data;
        $scope.loading = false;
    });
});

This is my Service:

angular.module('apartmentService', [])
.factory('Apartment', function ($http) {
    return {
        get: function (myLocation) {
            //return $http.get('/api/apartments');
            return $http({
                method: 'GET',
                url: '/api/apartments',
                //headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                params: {location: myLocation}
            });
        }
    };
});

And here is the HTML part:

<input type="text" name="myLocation" class="form-control" ng-model="myLocation">

I am trying to retrieve data from a GET method using AngularJS and pass it to params. How can I achieve this?

Answer №1

To ensure that a value from your form is passed as "location", you need to bind it to your model and then explicitly send it to your factory get function.

Here's a functional example where instead of the $http call, a window alert displays the typed-in data, but the concept remains the same.

http://plnkr.co/edit/fRra6RfQrSZb8rzrm4XF?p=preview

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3929d94869f9280919a8b9980c5d39e929a"><span class="__cf_email__" data-cfemail="06636463677e6354482c2132650725252025692e2220">[email protected]</span></a>" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <form ng-submit="getIt()">
      <input type="text" ng-model="myLocation"/>
      <input type="submit"/>
    </form>

  </body>

</html>

Javascript:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, Apartment) {
  $scope.name = 'World';
  $scope.myLocation = 'Hollywood';

  $scope.getIt = function() {
    Apartment.get($scope.myLocation);
  }
});

app.factory('Apartment', function ($window) {
        return {
            get: function (whatLocation) {
                $window.alert(whatLocation);
            }
        };
    });

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

What is the best way to load the route calculation dynamically?

I am struggling with calculating the Google Maps route dynamically. The console shows an error stating that 'calcularRuta' is not defined: Uncaught ReferenceError: calcularRuta is not defined at HTMLInputElement.onclick (index.html:1) Despi ...

Easily transform checkboxes into images using jQuery with no need for external plugins

Is it possible to replace checkboxes with images without using jQuery plugins? I'm hoping to achieve this in just a few lines of code. Thank you. ...

Angular - when removing items from ngRepeat, the remaining elements do not transition smoothly; instead, they abruptly snap or jump into position

Currently using AngularJS v1.4.8 with ngAnimate injected into my controller. In the process of creating a dynamic list using ngRepeat, tied to an array. The addition and updating of items in the list function smoothly with animations working as intended. ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Encountering issues with the functionality of async await

I am a beginner when it comes to utilizing the async, await, and promise features in JavaScript. My current focus is on: async function sendTextMessage(text) { console.log("----1----"); var messageData = { message: { text: tex ...

It is imperative that the HTML div element remains within the boundaries of the page

Let me begin by providing some context. I am currently developing a responsive page that uses percentages to position my divs, allowing users to drag and drop items wherever they please. However, a problem arises when the user positions an object too close ...

Issue with AngularJS directive not recognizing $filter function

/Hey there! .directive('rnDatatable', function($filter) { //Custom Table Directive return { scope : { ngTablefields : "=", ngTabledata : "=" }, restrict: 'AEC', link: function(scope, element, attrs) { ...

Using Ajax/jQuery in combination with Mongodb

My experience with Ajax/jQuery is fairly new. I am currently working on creating a sample HTML page using Ajax/jQuery to retrieve all customers and search for a customer by ID. Each customer has three variables: ID, firstName, and lastName. I am looking t ...

Adjust the opacity of a MeshBasicMaterial in real-time

<script type="importmap"> { "imports": { "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384c504a5d5d784e0816090e0a1608">[email p ...

Creating a modal popup when a button is clicked

After searching online for a way to make my sign up modal pop up when the signup button in my navbar is pressed, I was unable to find any information on how to achieve this. I suspect it involves JavaScript, but my knowledge of JS is limited. I attempted ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...

Populate a PHP array with designated file types from a designated folder, to later be loaded into a JavaScript array

My goal is to populate a JavaScript array with files of type .dae from different directories: "/collada/basement", "/collada/ground", "/collada/first", and "/collada/roof". I'm thinking of creating separate arrays for each directory. I understand that ...

sending an array variable to ajax in CakePHP

I am currently working on creating a feature similar to this where users can select multiple conditions for their search. My approach involves populating an array with the selected conditions and passing it through ajax to make a request. Below are snippet ...

Error: The program is encountering an issue because it is trying to scan a file that is not a directory in the "./src/functions/" path. This error message appears when the program encounters a "

node:internal/fs/utils:351 throw err; ^ Error: ENOTDIR: not a directory, scandir './src/functions/.DS_Store' at Object.readdirSync (node:fs:1532:3) at Object.<anonymous> (/Users/roopa/Desktop/projects/LLbot/src/bot.js:43:6 ...

Developer tools indicate React state property is set despite it always being undefined

Encountering a perplexing problem while using ReactJs along with TyperScript. In the constructor of the component, I initialize the state with a value from the provided props: constructor(props: IEditProps) { super(props); const initialState = { ...

What is the simplest method for fetching and parsing JSON data with jQuery and JavaScript?

I'm having trouble making this code snippet work. I can't seem to figure it out. The objective is to retrieve and parse a JSON object in the simplest and easiest way possible. Here's the code snippet. <!DOCTYPE html> <html> &l ...

How can I make the cssRenderer layer element transparent so that the webglRenderer layer is visible beneath it in Three.js?

A test is being conducted on a cssRenderer that is running a scene directly in front of a webglRender. This setup allows both to run together, creating the illusion of including html dom elements (div and text) in webgl. The goal is to make the textbox ba ...

Is there a way to efficiently parse HTML data returned as JSON in the browser using Cordova/Ionic?

Currently, I am retrieving data from a Drupal service and using AngularJS along with the ionic framework to create a hybrid app for mobile platforms, leveraging Cordova or Phonegap. You can check out my code on codepen: http://codepen.io/BruceWhealtonSWE/p ...

Troubleshooting resizing images in React using Material UI's useStyles

When attempting to resize an image using React, I am encountering a problem where adjusting the height and width of the tag with useStyles does not reduce the size of the image but instead moves it around on the page. Here is the code snippet: import { ma ...