Agent Zebra
Agent Zebra

Reputation: 4550

Integrating simple utility functions into angular app

I'm integrating a simple utility function into an angular app. How do I get the variable utc to show up on the page in my angular app? It's not showing up yet :( Here's the steps I took. Basically I guess I needed to refactor the following snippet into a service.

var offset = - new Date().getTimezoneOffset();
var utc = ((offset > 0 ? '+' : '') + offset / 60);
document.write(utc);

Here's my service... not sure if this is correct as it's not working yet.

(function () {
    'use strict';
    angular.module('weatherapp.weatherlist')
        .factory('utcFactory', function utcFactory() {
        return {
            myUTC: function() {
                var offset = - new Date().getTimezoneOffset();
                var utc = ((offset > 0 ? '+' : '') + offset / 60);
                return utc;
            }
        };
    }
})();

Here's the controller:

(function () {
    'use strict';
    angular.module('weatherapp.weatherlist', ['weatherapp.locations'])
        .controller('WeatherlistController', ['$scope', 'LocationService', 'WEATHER_API_URL', 'WEATHER_API_IMAGE_URL', 'WEATHER_API_ID', 'WeatherListFactory', 'utcFactory',WeatherListCtrl]);

    function WeatherListCtrl($scope, LocationService, WEATHER_API_URL, WEATHER_API_ID, WEATHER_API_IMAGE_URL, WeatherListFactory, utcFactory) {
        $scope.$on('$ionicView.enter', function(){
            $scope.locationData= [];
            //TODO Show empty String when no locations are set.
            var locations = LocationService.getLocations();
            $scope.noLocation=locations.length<1;
            if (!$scope.noLocation){
                locations.forEach(function (location) {
                    WeatherListFactory.getWeatherData(WEATHER_API_URL + 'q=' + location + '&appid=' + WEATHER_API_ID).then(function (response) {
                        response.data.weather[0].icon=WEATHER_API_IMAGE_URL+response.data.weather[0].icon+'.png';
                        $scope.locationData.push(response.data);
                    });
                });
            }
        });
    }
})();

Here's how I'm trying to bind it in the view, do I need anything else than this? <span class="tiny">{{utc}}</span>

What am I doing wrong? Is there a better way to approach this? Seems overkill for such a simple thing.

Upvotes: 0

Views: 55

Answers (1)

Sajal
Sajal

Reputation: 4401

The factory does not have its own scope. As you have already injected the utcFactory in the controller. Bind the return of service to $scope.utc as:

utcFactory.myUTC().then(function(results) { 
   $scope.utc = results.data;
});

Upvotes: 1

Related Questions