AngularJs JSON endpoint modifier

I've been working on a simple weather app in Angular for practice, but I've hit a roadblock.

Here's the Angular JSON feed I'm using:

app.factory('forecast', ['$http', function($http) { 
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,NL&lang=NL_nl&units=metric') 
        .success(function(data) { 
          return data; 
        }) 
        .error(function(err) { 
          return err; 
        }); 
}]);

The feed loads into index.html successfully. Now, what I want is an input form on index.html that allows users to change the city from Amsterdam in the URL mentioned above, located in js/services/forecast.js. This way, people can view the weather of different cities.

To see the demo, click here:

I've tried numerous options over the past three days, but nothing seems to work. What is the correct approach here?

Answer №1

Start by setting up a "configurable" service :

app.factory('weatherService', ['$http', function($http) { 
    var city;
    var cities = {
        amsterdam: 'Amsterdam,NL',
        paris: 'Paris,FR'
    };
    var api_base_url = 'http://api.openweathermap.org/data/2.5/weather';
    var other_params = 'lang=NL_nl&units=metric';

    return {
        setCity: function(cityName){
            city = cityName ;
            console.log(city);
        },
        getWeather: function(cityName){
          console.log(city);
            if(cityName) this.setCity(cityName);
            if (!city) throw new Error('City is not defined');
            return $http.get(getURI());
        }
    }

    function getURI(){
        return api_base_url + '?' + cities[city] + '&' + other_params;
    }
}]);

Next, create a controller using the code below:

app.controller('forecastController', ['$scope', 'weatherService',function($scope,weatherService){

$scope.city = 'amsterdam' ;

    $scope.$watch('city',function(){
      console.log($scope.city);
      weatherService.setCity($scope.city);
    });

$scope.getWeather = function(){
  console.log('getting weather');
    weatherService.getWeather()
    .success(function(data){
    console.log('success',data);
    $scope.weatherData = data;
    }).error(function(err){
      console.log('error',err);
      $scope.weatherError = err; 
    });    
}; 
}]);

Create a template like the one shown below

<link rel="stylesheet" href="style.css" />

<div data-ng-controller="forecastController">

  <form>

    <label>
      <input type="radio" name="city" data-ng-model="city" data-ng-value="'amsterdam'">Amsterdam
    </label>
    <br/>
    <label>
      <input type="radio" name="city" data-ng-model="city" data-ng-value="'paris'">Paris
    </label>
    <br/>

    <button data-ng-click="getWeather()">Get Weather</button>

  </form>  

  <p class="weather-data">
    {{weatherData}}
  </p>
  <p class="weather-error">
    {{weatherError}}
  </p>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>

To see the functionality in action, click here : http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8?p=preview

Answer №2

To incorporate a function in your factory, you can define your forecast as follows:

app.factory('forecast', ['$http', function($http) { 
 return {
     query: function(city) {
         return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&lang=NL_nl&units=metric') 
        .success(function(data) { 
          return data; 
        }) 
        .error(function(err) { 
          return err; 
        });
     }
 };

}]);

After defining the function in your factory, you can utilize it in your controller like this:

forecast.query('Amsterdam,NL').success(function(data) {
  $scope.weather = data;
});

Answer №3

Enhance the service code by creating a dedicated method that can be called multiple times with varying parameters (cities):

app.factory('forecast', ['$http', function($http) {
    return {
        load: function(location) {
            return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + location + '&lang=NL_nl&units=metric')
            .success(function(data) {
                return data;
            })
            .error(function(err) {
                return err;
            });
        }
    }
}]);

This modification allows for loading forecasts for different locations in the controller when needed:

forecast.load('Amsterdam,NL').then(function(data) {
    $scope.weather = data;
});

Check out the demo here: http://plnkr.co/edit/GCx35VxRoko314jJ3M7r?p=preview

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

AngularJS templateUrl changes on page refresh``

I am currently using an angular packet template that consists of 11 pages, each with a corresponding button. The route code for this template is as follows: state('app.pagelayouts.fixedsidebar1', { url: "/fixed-sidebar", templateUrl: "assets ...

Importing and Extracting JSON Data Using PHP

I am currently developing a logging system for my PHP software. To collect data, I am utilizing the API from https://ipinfo.io/ As depicted in the screenshot, you can simply use json_decode to read the retrieved information. The only issue lies with the ...

The input tag contains an empty Request.Form

My issue lies in using Request.Form to retrieve text from an input field, as the value always ends up being empty. My goal is to extract the text value from the input tag and use it to query my database. I have attempted to write to an ASP TextBox but enco ...

Position the vertical bar directly adjacent to the form input field

Looking for assistance with creating a unique webpage layout that includes a form where the employee ID is visually separated from the rest of the content by a vertical bar extending across the entire page. However, my attempts to achieve this using a gr ...

Submitting a JSON array to an MVC Web API using the POST method

Here is the code snippet I am using: { "myImage": [{ "Image": "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACGUlEQVR4nI2OPWgTcRiHf/9L7isftmkbU/PRYg/LgaI4CBWKCkoCSqVgRTqo6OIgOrgpgojUyUHwA1xEHIUKNggq1ASili6G1sXUVE0ThV4vmNSD3l3u7u/SgGlszG9+nud9gTY2LU ...

What is the process for converting a Py3k HTTPResponse into json.load?

It was my understanding that json.load() would be able to process objects in the same way as http.client.HTTPResponse, but it seems to be encountering an issue with the read() function being treated as a bytes-like object. (I am working with Python 3.3.) S ...

Manually adjust rotation in Three.js by clicking

I am looking to initiate an animated rotation of an object by clicking a button. I have a basic understanding that the render function operates as an infinite loop and that adding 0.1 to cylinder.rotation.x continuously rotates the object. My goal is to ...

Personalized data based on the language within Next.js

Is there a way to customize Metadata for users based on search engine keywords? To enhance SEO performance on my website, I am working on setting up unique Metadata for the two languages my website supports: English and Portuguese. Specifically, I aim to ...

sequentially animating elements using animate css in a choreographed manner

I have created a unique jsfiddle with 20 boxes that I am trying to animate using the Animate.css plugin. The plugin can be found at daneden.me/animate. My goal is to animate each box one after the other in a sequential manner, but I seem to be having trou ...

The data is not being filtered properly in Ionic Angularjs

Below is the code for my controller: $scope.professionList = []; $scope.searchText = ''; $scope.$on('$ionicView.enter', function() { PeopleSearchService.setSearchParams(undefined); }) $scope.$on('$ionicView.loaded', funct ...

Tips for managing submitted data to a server in express?

In the process of sending a post request from my index.js to app.js upon a click event, I have the following code snippet: var data = { name: "Sarah", age: "21" }; var xhr = new XMLHttpRequest(); xhr.open("POST", "/", true); xhr.setRequestHe ...

What is the best way to implement an onReady promise in a JavaScript application?

Exploring some Advanced topics in JS I am currently diving into and there is an interesting concept that's piqued my curiosity. I've been developing a VueJS application and now I'm looking to expose certain data and even methods from Vue ou ...

DOM not getting updated by ng-repeat when dynamically inserting elements

Utilizing jsonForm to create a dynamic form using 3 different JSON schemas. Each form submission triggers the display of the next form until all 3 forms are filled in. The data from all 3 forms is then combined into one JSON object, which is sent back and ...

Issue with Textarea not updating when props change in a React component

I am facing an issue with updating the default value of a textarea based on props passed from a parent component. Strangely, the update works when using 'value' but not when using 'defaultValue'. However, I need the textarea to be edita ...

When I trigger a function by clicking, I also set a timeout of 1 second. Is it possible to deactivate this timeout from within the function itself?

One button triggers a function with a timeout that repeats itself upon clicking. Here's the code snippet: function chooseNum() { let timeout = setTimeout(chooseNum, 1000); } To disable this repeating function, I attempted another function like so ...

Implementing the onClick function for the correct functionality in a ReactJS map component

I have designed a mockup and now I am trying to bring it to life by creating a real component. View my component mockup here Starting with something simple, I created 3 buttons and an array. However, when I click on any button, all features are displayed ...

Restrictions on file sizes when using multer for file uploads

I am currently working on a file uploader that needs to support various file types, such as images and videos. My goal is to apply different maximum file sizes for images (10MB) and videos (100MB) using a single instance of Multer, a middleware designed fo ...

What Causes the Response to Vary in a Post Request?

Issue: When I use console.log(res.data), it shows different data compared to console.log(JSON.parse(res.request.response)). My Next.js application is sending a post request to an internal API. The response from the REST endpoint should contain a list obje ...

JavaScript heap ran out of memory near heap limit during mark-compacts, rendering the allocation ineffective, resulting in a failed Ionic 3 production build

While attempting to build a production version of my Ionic 3 app, I encountered the following error: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory". To troubleshoot this issue, I duplicated the en ...

What is the best way to retrieve the value of a selected button from a v-btn-toggle?

<v-btn-toggle v-model="toggle_one"> <v-btn flat> CAD50 </v-btn> <v-btn flat> CAD100 </v-btn> <v-btn flat> CAD1000 </v-btn> <v-btn flat> CAD10000 </v-btn> ...