Weather
by Aqilah Misuary
HTML
<script src="http://code.angularjs.org/1.1.4/angular.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<div ng-app="myapp" ng-controller="WeatherCtrl">
<h2>Weather in Singapore</h2>
<weather-icon cloudiness="{{ weather.clouds }}"></weather-icon>
<h3>Current: {{ weather.temp.current | temp:2 }}</h3>
min: {{ weather.temp.min | temp }}, max: {{ weather.temp.max | temp }}
</div>
JavaScript
'use strict';
var myapp = angular.module('myapp', []);
myapp.factory('weatherService', function($http) {
return {
getWeather: function() {
var weather = { temp: {}, clouds: null };
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?q=Singapore&units=metric&callback=JSON_CALLBACK').success(function(data) {
if (data) {
if (data.main) {
weather.temp.current = data.main.temp;
weather.temp.min = data.main.temp_min;
weather.temp.max = data.main.temp_max;
}
weather.clouds = data.clouds ? data.clouds.all : undefined;
}
});
return weather;
}
};
});
myapp.filter('temp', function($filter) {
return function(input, precision) {
if (!precision) {
precision = 1;
}
var numberFilter = $filter('number');
return numberFilter(input, precision) + '\u00B0C';
};
});
myapp.controller('WeatherCtrl', function ($scope, weatherService) {
$scope.weather = weatherService.getWeather();
});
myapp.directive('weatherIcon', function() {
return {
restrict: 'E', replace: true,
scope: {
cloudiness: '@'
},
controller: function($scope) {
$scope.imgurl = function() {
var sun = 'https://dl.dropboxusercontent.com/u/30075450/sun.jpg';
var partlycloudy = 'https://dl.dropboxusercontent.com/u/30075450/semicloudy.jpeg';
var cloudy = 'https://dl.dropboxusercontent.com/u/30075450/cloudy.jpg';
if ($scope.cloudiness < 20) {
return sun;
} else if ($scope.cloudiness < 90) {
return partlycloudy;
} else {
return cloudy;
}
};
},
template: '<div style="float:left"><img ng-src="{{ imgurl() }}"></div>'
};
});