AngularJs json URL changer
First, create a "configurable" service :
app.factory('forecast', ['$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; }}]);
Then you can create a controller like the following:
app.controller('forecastCtrl', ['$scope', 'forecast',function($scope,forecast){$scope.city = 'amsterdam' ; $scope.$watch('city',function(){ console.log($scope.city); forecast.setCity($scope.city); });$scope.getWeather = function(){ console.log('get weather'); forecast.getWeather() .success(function(data){ console.log('success',data); $scope.weatherData = data; }).error(function(err){ console.log('error',err); $scope.weatherError = err; }); }; }]);
To implement a template as the following
<link rel="stylesheet" href="style.css" />
<div data-ng-controller="forecastCtrl"> <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>
You can view the code working here : http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8?p=preview
You can return a function in your factory. Define your forcast
as
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; }); } };}]);
Then in your controller
forecast.query('Amsterdam,NL').success(function(data) { $scope.weer = data;});
Change service code to have a dedicated method which you can call multiple times with different 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; }); } }}]);
Then in controller you would be able to load forecat for other locations when you need:
forecast.load('Amsterdam,NL').then(function(data) { $scope. weer = data;});