Currently, I am in the process of developing a weather application using Angular 1.5.8 where users should have the option to switch between imperial and metric units for temperature and wind speed.
The toggle feature along with all the weather data fetched from an external API are placed in separate directives. However, I am considering consolidating the temperature and wind speed information into the same directive as the toggle feature, and then utilizing either $broadcast or $emit to showcase the data and conversions within the weather directive. Do you think this approach is the most effective way to achieve this? If not, what alternative method would you suggest?
Here is the directive containing the toggle:
app.directive('topBar', topBar);
function topBar() {
return {
template:
'<div class="changeTemp" ng-click="vm.changeTempUnit()">' +
'<span ng-class="vm.fahrClass">°F</span>' +
'<span>/</span>' +
'<span ng-class="vm.celsClass">°C</span>' +
'</div>',
restrict: 'E',
scope: {},
controller: TopBarController,
controllerAs: 'vm'
};
}
function TopBarController() {
var vm = this;
vm.celsClass = 'unselected';
vm.changeTempUnit = changeTempUnit;
vm.fahrClass = 'selected';
vm.temp;
vm.windSpeed;
function changeTempUnit() {
if (vm.fahrClass === "selected") {
vm.fahrClass = 'unselected'; // Fahrenheit unselected
vm.celsClass = 'selected'; // Celsius selected
vm.temp = Math.round((vm.temp - 32) * 5 / 9); // Celsius
vm.windSpeed = (vm.speed * 0.44704).toFixed(0); // M/S
} else if (vm.celsClass === 'selected') {
vm.celsClass = 'unselected'; // Celsius unselected
vm.fahrClass = 'selected'; // Fahrenheit selected
vm.temp = Math.round(vm.temp * 1.8 + 32); // Fahrenheit
vm.windSpeed = (vm.speed / 0.44704).toFixed(0); // MPH
}
}
}
Below is the directive responsible for displaying the weather:
app.directive('weather', weather);
function weather() {
return {
template:
'<div>' +
'Temp: {{vm.temp}}°' + '<br>' +
'Wind Speed: {{vm.windSpeed}}' +
'</div>',
restrict: 'E',
scope: {},
controller: WeatherController,
controllerAs: 'vm'
};
}
WeatherController.$inject = ['weatherService'];
function WeatherController(weatherService) {
var vm = this;
vm.temp;
vm.windSpeed;
activate();
function activate() {
return weatherService.getWeather().then(function(data) {
weatherInfo(data);
});
}
function weatherInfo(data) {
vm.temp = Math.round(data.main.temp); // Fahrenheit
vm.windSpeed = (data.wind.speed).toFixed(0); // MPH
}
}