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