Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div ng-app="LocalWeatherApp" class="jumbotron jumbotron-main" background-changer-directive ng-cloak>
    <loading class="loading-indicator"></loading>
    <div class="container" ng-controller="WeatherController as weatherCtrl">
      <weather-component name="weatherCtrl.locationName" title="{{weatherCtrl.title}}" address="weatherCtrl.address"></weather-component>
      <weather-widget class="changeColor" temperature-data="weatherCtrl.temperatureData" units="weatherCtrl.units"></weather-widget>
      <div class="alert alert-danger text-center" ng-if="weatherCtrl.locationError">
        <strong>Error!</strong> Cannot retrieve your location at this time. Enable location for your device and try again.
      </div>
      <div class="alert alert-danger text-center" ng-if="weatherCtrl.weatherError">
        <strong>Error!</strong> Cannot retrieve your weather for your location. Set your location to get accurate weather.
      </div>
    </div>
  </div>
              
            
!

CSS

              
                [ng\:cloak], [ng-cloak], .ng-cloak {
  display: none !important;
}

.loading-indicator {
    display: block;
    width: 70px;
    position: fixed;
    left: 0;
    right: 0;
    margin: 0 auto;
    top: 40%;
    z-index: 100;
    background-color: #FFF;
}

.loading-indicator img {
    width: 70px;
    background-color: #FFF;
}

#mainTitle {
}

#mainAddress {
  color: darkgoldenrod;
}

#addressText {
  font-weight: bold;
}

/*#locationText {
  color: blue;
}*/

.nav-pills a {
    cursor: pointer;
}


.jumbotron-main {
  height: 100vh;
  margin-top: 0;
  padding-top: 0;
  margin-bottom: 0;
  padding-bottom: 0;
  background: #ffffff url("https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480108240/Weather/Weather_Default.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;

}

body {
  color: white;
}

.mainContainer {
  color: black;
}

.changeColor {
  color: black;
}
              
            
!

JS

              
                (function() {

'use strict';

angular.module('LocalWeatherApp', ['ngSanitize'])
.controller('WeatherController', WeatherController)
.controller('TemperatureIconsController', TemperatureIconsController)
.controller('BackgroundChangeController', BackgroundChangeController)
.service('LocationService', LocationService)
.service('WeatherService', WeatherService)
.constant('LocationBasePath', "http://api.ipstack.com/check")
 .constant("LocationKey",
 "b98e187cfa06655d41fb85ebae0d8fc5")
.constant('WeatherBasePath', "https://api.openweathermap.org/")
.constant('WeatherApiKey', "72b63a871c87feeaebbcbde6d7c635f7")
.constant('IconToBackgroundMapping', {
    "01d": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480108905/Weather/01d_ehmvqo.jpg",
    "01n": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480112703/Weather/01n.jpg",
    "02d": "https://res.cloudinary.com/jawadrashid/image/upload/v1480112846/Weather/02d.jpg",
    "02n": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480112944/Weather/02n.jpg",
    "03d": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480113130/Weather/03d.jpg",
    "03n": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480113345/Weather/03n.jpg",
    "04d": "https://res.cloudinary.com/jawadrashid/image/upload/v1480116817/Weather/04d.jpg",
    "04n": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480116944/Weather/04n.jpg",
    "09d": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480117139/Weather/09d.jpg",
    "09n": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480117210/Weather/09n.jpg",
    "10d": "https://res.cloudinary.com/jawadrashid/image/upload/v1480117808/Weather/10d.jpg",
    "10n": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480117443/Weather/10n.jpg",
    "11d": "https://res.cloudinary.com/jawadrashid/image/upload/v1480117862/Weather/11d.jpg",
    "11n": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480118023/Weather/11n.jpg",
    "13d": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480118213/Weather/13d.jpg",
    "13n": "https://res.cloudinary.com/jawadrashid/image/upload/v1480118218/Weather/13n.jpg",
    "50d": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480118333/Weather/50d.jpg",
    "50n": "https://res.cloudinary.com/jawadrashid/image/upload/c_scale,w_1920/v1480118360/Weather/50n.jpg"
})
.component('loading', {
    template: '<img src="https://res.cloudinary.com/jawadrashid/image/upload/v1479984923/Weather/spinner.svg" ng-if="$ctrl.show">',
    controller: LoadingController
})
.component('weatherComponent', {
    template: '<h1 class="text-center" id="mainTitle"> {{$ctrl.title}}</h1>\
               <h2 ng-if="$ctrl.address != \'\'" class="text-center" id="mainAddress">Showing Weather for <span id="addressText">{{$ctrl.address}}</span></h2>\
               <h2 ng-if="$ctrl.name != \'\'" class="text-center" id="locationName"><b>Location:</b> <span id="locationText">{{$ctrl.name}}</span></h2>',
    bindings: {
        title: '@',
        address: '<',
        name: '<'
    }
})
.component('weatherWidget', {
    template: '\
        <div class="row">\
            <div class="col-sm-8 col-sm-offset-2">\
                <div class="container">\
                    <temperature-icons-widget temperature-data="$ctrl.temperatureData" units="$ctrl.units"></temperature-icons-widget>\
                </div>\
            </div>\
        </div>',
    bindings: {
        temperatureData: '<',
        units: '<'
    }
})
.component('temperatureIconsWidget', {
    template: '<div class="well">\
                    <ul class="nav nav-pills nav-justified" ng-if="$ctrl.temperatureData">\
                        <li role="presentation" ng-class="{active: $ctrl.units == \'C\'}"><a ng-click="$ctrl.changeUnits(\'C\')">Celsius(°C)</a></li>\
                        <li role="presentation" ng-class="{active: $ctrl.units == \'F\'}"><a ng-click="$ctrl.changeUnits(\'F\')">Farenheit(°F)</a></li>\
                    </ul>\
                    <div ng-if="$ctrl.temperatureData">\
                        <br>\
                        <div class="text-center" ng-if="$ctrl.temperatureData.temperature">\
                            <b>Temperature:</b> {{$ctrl.getTemperature($ctrl.temperatureData.temperature) | number:1}} °{{$ctrl.units}} \
                        </div>\
                        <div class="text-center" ng-if="$ctrl.temperatureData.humidity">\
                            <b>Humidity:</b> {{$ctrl.temperatureData.humidity}} %\
                        </div>\
                        <div class="text-center" ng-if="$ctrl.temperatureData.pressure">\
                            <b>Humidity:</b> {{$ctrl.temperatureData.pressure}} hpa\
                        </div>\
                        <div class="text-center" ng-if="$ctrl.temperatureData.clouds">\
                            <b>Cloudiness:</b> {{$ctrl.temperatureData.clouds}} %\
                        </div>\
                        <div class="text-center" ng-if="$ctrl.temperatureData.wind">\
                            <b>Wind Speed:</b> {{$ctrl.temperatureData.wind}} m/s\
                        </div>\
                        <div class="text-center" ng-if="$ctrl.temperatureData.weather && $ctrl.temperatureData.weather.length > 0">\
                            <span ng-bind-html="$ctrl.getWeatherConditions()"></span>\
                        </div>\
                        <div class="text-center" >\
                            <b>Time Right Now:</b> <span>{{$ctrl.getCurrentTime() | date:"MMM d, y h:mm:ss a Z"}}</span>\
                        </div>\
                    </div>\
                </div>',
    bindings: {
        temperatureData: '<'
    },
    controller: TemperatureIconsController
})
.directive('backgroundChangerDirective', BackgroundChangerDirective)
.factory('loadingHttpInterceptor', LoadingHttpInterceptor)
.config(config);



WeatherController.$inject = ['LocationService', 'WeatherService', '$rootScope', 'WeatherBasePath']
function WeatherController(LocationService, WeatherService, $rootScope, WeatherBasePath) {
    var ctrl = this;
    ctrl.title = 'Current Weather App';
    ctrl.locationError = false;
    ctrl.weatherError = false;
    ctrl.address = "";
    ctrl.weather = "";
    ctrl.locationObj = null;
    ctrl.weatherObj = null;
    ctrl.units = 'C';

    ctrl.$onInit = function() {
        LocationService.getLocation().then(ctrl.locationSuccessCallback, ctrl.locationErrorCallback);
    }

    ctrl.locationSuccessCallback = function(response) {
        ctrl.address = response.address;
        ctrl.locationObj = response;
        // console.log("Location Success Callback", response);

        WeatherService.getWeather(ctrl.locationObj.longitude, ctrl.locationObj.latitude)
                      .then(ctrl.weatherSuccessCallback, ctrl.weatherErrorCallback);
    }

    ctrl.locationErrorCallback = function(response) {
        ctrl.locationError = true;
    }

    ctrl.weatherSuccessCallback = function(response) {
        // console.log("Weather Success Callback", response);
        ctrl.weatherObj = response;

        if(isKeyInObject("locationName", ctrl.weatherObj)) {
            ctrl.locationName = ctrl.weatherObj.locationName;
        }
        ctrl.temperatureData = response;
        ctrl.changeBackground(); 
    } 

    ctrl.changeBackground = function() {
        if(ctrl.weatherObj.weather && ctrl.weatherObj.weather.length > 0) {
            $rootScope.$broadcast('background:changed', {icon: ctrl.weatherObj.weather[0].icon});
        }
    }

   
    ctrl.weatherErrorCallback = function(response) {
        ctrl.weatherError = true;
    }
}


LocationService.$inject = ['$http', 'LocationBasePath', '$q', 'LocationKey']
function LocationService($http, LocationBasePath, $q, LocationKey) {
    var service = this;

    service.getLocation = function() {
        return $http.get("https://cors-anywhere.herokuapp.com/" + LocationBasePath + "?access_key=" + LocationKey).then(service.locationSuccess);
    }

    service.locationSuccess = function(response) {
      console.log(response);
        var data = response.data;
        // console.log("Raw Location Response", data);
        if("longitude" in data && "latitude" in data 
            && data["longitude"] != 0 && data["longitude"] != undefined 
            && data["latitude"] != 0 && data["latitude"] != undefined ) {

            var locationResponse = {
                longitude: data.longitude,
                latitude: data.latitude
            };
            var address = "";

            if("ip" in data && data["ip"] != "" && data["ip"] != undefined) {
                locationResponse.ip = data.ip;
            }
            if("city" in data && data["city"] != "" && data["city"] != undefined) {
                address += data.city;
            }
            if("country_name" in data && data["country_name"] != "" && data["country_name"] != undefined) {
                if(address != "") {
                    address += ", ";
                }
                address += data.country_name;
            }
            locationResponse.address = address;
            return locationResponse;
        } else {
            return $q.reject('Location Data Not Available');
        }
        
    }

}


WeatherService.$inject = ['$http', 'WeatherBasePath', 'WeatherApiKey']
function WeatherService($http, WeatherBasePath, WeatherApiKey) {
    var service = this;

    service.getWeather = function(longitude, latitude) {
        return $http({
            method: "GET",
            url: (WeatherBasePath + "data/2.5/weather"),
            params: {
                lat: latitude,
                lon: longitude,
                appid: WeatherApiKey,
                units: "metric"
            }
        }).then(service.weatherSuccess);
    }

    service.weatherSuccess = function(response) {
        // console.log("Weather Success In Weather Service", response);
        var data = response.data;
        if(isKeyInObject("main", data) && isKeyInObject("temp", data["main"])) {
            var weatherResponse = {};
            weatherResponse.temperature = data.main.temp;
            
            if(isKeyInObject("temp_min", data["main"])) {
                weatherResponse.minTemperature = data.main.temp_min;
            }
            if(isKeyInObject("temp_max", data["main"])) {
                weatherResponse.maxTemperature = data.main.temp_max;
            }
            if(isKeyInObject("pressure", data["main"])) {
                weatherResponse.pressure = data.main.pressure;
            }
            if(isKeyInObject("humidity", data["main"])) {
                weatherResponse.humidity = data.main.humidity;
            }

            if(isKeyInObject("name", data)) {
                weatherResponse.locationName = data.name;
            }
            if(isKeyInObject("cod", data)) {
                weatherResponse.code = data.cod;
            }
            if(isKeyInObject("weather", data)) {
                weatherResponse.weather = data.weather;
            }
            

            if(isKeyInObject("sunrise", data["sys"])) {
                weatherResponse.sunrise = data.sys.sunrise;
            }
            if(isKeyInObject("all", data["clouds"])) {
                weatherResponse.clouds = data.clouds.all;
            }
            if(isKeyInObject("sunset", data["sys"])) {
                weatherResponse.sunset = data.sys.sunset;
            }
            if(isKeyInObject("speed", data["wind"])) {
                weatherResponse.wind = data.wind.speed;
            }

            return weatherResponse;
        } else {
            return $q.reject("Weather data is missing");
        }
    }

}

TemperatureIconsController.$inject = ['WeatherBasePath']
function TemperatureIconsController(WeatherBasePath) {
    var ctrl = this;
    ctrl.units = 'C';
    
    ctrl.getTemperature = function(temp) {
        var temperature;
        if(ctrl.units == "C") {
            temperature = temp;
        } else {
            temperature = (temp * (9/5)) + 32;
        }
        return temperature;
    }

    ctrl.changeUnits = function(unit) {
        ctrl.units = unit;
    }

    ctrl.getWeatherConditions = function() {
        var weatherCondition = "";

        for(var i = 0;i < ctrl.temperatureData.weather.length;i++) {
            var condition = ctrl.temperatureData.weather[i];
            
            if(i > 0) {
                weatherCondition += " ";
            }
            weatherCondition += ("<img src='" + ctrl.getConditionLogo(condition) + "' > " + condition.main);
        }

        // console.log($compile(weatherCondition)($scope));
        return weatherCondition;
    }

   
    ctrl.getConditionLogo = function(condition) {
        return WeatherBasePath + "img/w/" + condition.icon + ".png";
    }

    ctrl.getCurrentTime = function() {
        return new Date();
    }

}

function BackgroundChangerDirective() {
    var ddo = {
        restrict: 'A',
        scope: {},
        controller: 'BackgroundChangeController',
        controllerAs: 'backgroundChangedCtrl',
        bindToController: true,
        link: BackgroundChangedDirectiveLink
    };

    return ddo;
}

BackgroundChangeController.$inject = ['$scope', 'IconToBackgroundMapping']
function BackgroundChangeController($scope, IconToBackgroundMapping) {
    var backgroundChangedCtrl = this;
    backgroundChangedCtrl.backgroundUrl = "";

    $scope.$on('background:changed', function(event, data) {
        // console.log("In Controller Changed", event, data);
        // console.log(IconToBackgroundMapping);
        if(data.icon != "") {
            backgroundChangedCtrl.backgroundUrl = IconToBackgroundMapping[data.icon];
        }
    });
}

function BackgroundChangedDirectiveLink(scope, element, attr, controller) {
    scope.$watch('backgroundChangedCtrl.backgroundUrl', function(newValue, oldValue) {
        // console.log("Background Changed");
        if(newValue != "") {
            element.css('background-image', 'url(' + newValue + ')');
        }
    });
}


LoadingController.$inject = ['$rootScope']
function LoadingController($rootScope) {
    var $ctrl = this;
    var listener;

    $ctrl.$onInit = function() {
        $ctrl.show = false;
        listener = $rootScope.$on('spinner:activate', onSpinnerActivate);
    }

    $ctrl.$onDestroy = function() {
        listener();
    }

    function onSpinnerActivate(event, data) {
        $ctrl.show = data.on; 
    }
}

LoadingHttpInterceptor.$inject = ['$rootScope', '$q']
function LoadingHttpInterceptor($rootScope, $q) {
    var loadingCount = 0;
    var loadingEventName = 'spinner:activate';

    return {
        request: function (config) {
            if(++loadingCount == 1) {
                $rootScope.$broadcast(loadingEventName, {on: true});
            }

            return config;
        },

        response: function(response) {
            if(--loadingCount == 0) {
                $rootScope.$broadcast(loadingEventName, {on: false});
            }

            return response;
        },

        responseError: function (response) {
            if(--loadingCount == 0) {
                $rootScope.$broadcast(loadingEventName, {on: false});
            }

            return $q.reject(response);
        }
    }
}



config.$inject = ['$httpProvider'];
function config($httpProvider) {
  $httpProvider.interceptors.push('loadingHttpInterceptor');
}

function isKeyInObject(key, object) {
    return (key in object && object[key] != "" && object[key] != undefined);
}


})();
              
            
!
999px

Console