In this article, let us see, How to create a web based weather widget using Angular JS. Copy the below Javascript snippet and save it as script file with .js as extension. In this example I am using Chennai as the location. Open Weather Map api is used to fetch weather details
JavaScript
var app = angular.module('weatherApp', []); app.controller('weatherCtrl', ['$scope', 'weatherService', function($scope, weatherService) { function fetchWeather(zip) { weatherService.getWeather(zip).then(function(data) { $scope.place = data; }); } fetchWeather('600091); $scope.findWeather = function(zip) { $scope.place = ''; fetchWeather(zip); }; }]); app.factory('weatherService', ['$http', '$q', function($http, $q) { function getWeather(zip) { var deferred = $q.defer(); $http.get('http: //api.openweathermap.org/data/2.5/forecast/daily?q=%27+chennai+%27&mode=json&units=metric’) .success(function(data) { deferred.resolve(data); }) .error(function(err) { console.log('Error retrieving markets'); deferred.reject(err); }); return deferred.promise; } return { getWeather: getWeather }; }]);
HTML
<!DOCTYPE html> <html ng-app="weatherApp"> <head> <meta charset="utf-8″ /> <title> AngularJS Plunker </title> <link data-require="bootstrap-css@3.1.1″ data-semver="3.1.1″ rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" /> <script> document.write(‘<base href="‘ + document.location + ‘" />’); </script> <link rel="stylesheet" href="style.css" /> <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js” data-semver="1.2.16″> </script> <script data-require="jquery@*" data-semver="2.0.3″ src="http://code.jquery.com/jquery-2.0.3.min.js"> </script> <script data-require="bootstrap@*" data-semver="3.1.1″ src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"> </script> <script src="app.js"> </script> </head> <body ng-controller="weatherCtrl"> <form> <div class="form-group"> <input class="form-control" type="number" ng-model="zip" placeholder="e.g. 84105″ /> <input class="btn btn-default" type="submit" value="Search" ng-click="findWeather(zip)" /> </div> </form> <p ng-show="zip"> Searching the forecasts for: {{zip}} </p> <div> <h1> Forecast For {{ place.city.name}} </h1> <div class="col-xs-6″> <div class="panel panel-primary"> <div class="panel-heading"> <h4> <img class="img-thumbnail forecast-img" ng-src="http://openweathermap.org/img/w/{{ place.list[0].weather[0].icon }}.png" /> </h4> </div> <div class="panel-body"> <p> H: {{ place.list[0].temp.day }}° C </p> </div> </div> </div> </div> </body> </html>
Create a HTML code and copy and paste the below code: (this will show weather as well as image of the weather)
Leave a comment