,

AngularJS Weather App Tutorial #33

Posted by


Angular JS Weather App Tutorial

In this tutorial, we will create a simple weather app using Angular JS. We will use the OpenWeatherMap API to fetch weather data for a location and display it in our app.

Step 1: Setting up the project

First, make sure you have Angular JS installed in your project. You can include it from a CDN like below:

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

Next, create a new HTML file and add the following code to set up the Angular JS app:

<!DOCTYPE html>
<html>
<head>
    <title>Weather App</title>
</head>
<body ng-app="WeatherApp">
    <div ng-controller="WeatherController">
        City: <input type="text" ng-model="city">
        <button ng-click="getWeather()">Get Weather</button>
        <h2>Weather in {{city}}</h2>
        <p>{{weather.main.temp}}°C</p>
        <p>{{weather.weather[0].description}}</p>
    </div>

    <script>
        var app = angular.module('WeatherApp', []);
        app.controller('WeatherController', function($scope, $http) {
            $scope.city = '';
            $scope.weather = {};

            $scope.getWeather = function() {
                $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + $scope.city + '&appid=YOUR_API_KEY&units=metric')
                    .then(function(response) {
                        $scope.weather = response.data;
                    });
            };
        });
    </script>
</body>
</html>

Step 2: Getting the API key

To use the OpenWeatherMap API, you will need to create an account on their website and generate an API key. Replace YOUR_API_KEY in the URL with your actual API key.

Step 3: Understanding the code

In our Angular JS app, we have defined a module called WeatherApp and a controller called WeatherController. The controller has a city variable to store the user input for the city name and a weather variable to store the weather data fetched from the API.

The getWeather function sends a GET request to the OpenWeatherMap API with the user-provided city name. Once the response is received, the weather data is assigned to the weather variable, which is then displayed in the HTML.

Step 4: Testing the app

Save the HTML file and open it in a web browser. Enter a city name in the input field and click the "Get Weather" button. The app should fetch the weather data from the API and display it on the page.

Congratulations! You have successfully created a weather app using Angular JS. You can further enhance the app by adding more features such as displaying additional weather information, using geolocation to get the user’s current location, or adding error handling for invalid city names. Happy coding!