Promises dont get resolved. Alasql doesnt import CSV - javascript

I cant figure out what the error is. I try to read out a CSV from my server and then to access the DateValues with an FUnction Called getZinsAnDatum.
The Chain begins in function:
$scope.calcZins = function database(ctrl, $scope) {....
I chained the results, reading out my CSV-Values via
getZinsAnDatum(dateee, fullDate)
works when I click twice or wait and click again. Guess it works, after clicking two times, because its load into the cache. The function itself returns a promise too, after i get Warning from this, pointing on the code lines from getZinsAnDatum(dateee, fullDate):
Warning: a promise was created in a handler at /localhost:8383/validations/js/index.js:269:17 but was not returned from it
Sorry if I miss fundamental concepts.
I guess the Promises arent chained right or its to much traffic, because for every Value i detect (about 200) it downloads the hole CSV? therefore I wanted to inject the CSV once in my Alasql database and work from there.
But putting it in doesnt seem to work. Therefore could you help me out maybe? Down my code HTML and javascript:
I spared out some functions and variables, all variables are given and defined.
Javascript:
/* global $scope, user,user.anpDat, user.zinsDiff, user.zinsJetz,user.zinsNext, user.nextAnpDat, user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum , user.Berechnung, ctrl.Berechnung, Promise, alasql*/
angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache']).controller('AppCtrl', function ($scope) {
this.fullDate = new Date("1999-12-20");
this.fullDate2 = new Date("2000-01-20");
this.fullDate3 = new Date("2010-03-19");
this.date = fullDate.toISOString().substring(0, 10);
this.date2 = fullDate2.toISOString().substring(0, 10);;
this.date3 = fullDate3.toISOString().substring(0, 10);;
var data = {};
var url = 'tests/fib.csv';
function getZinsAnDatum(dateee, fullDate) {
return new Promise(function (resolve, reject) {
alasql.promise('SELECT [1] FROM CSV("tests/fib.csv", {headers:false, }) WHERE [0] >=? AND [1]!="."', [dateee])
.then(function (data) {
var temp = data [1 ][1];
resolve(temp);
}).catch(function (err) {
console.log('Error:', err);
});
});
}
$scope.calcZins = function database(ctrl, $scope) {
this.mybase = new alasql.Database('mybase');
this.mybase.exec('CREATE TABLE one ');
this.mybase.exec('SELECT [0][1] INTO one FROM CSV("tests/fib.csv", {headers:false, })');
//this.mybase.exec('PRINT one'); //GIVES ERRORS, CANT READ UNDEFINED JSON Object
calcZins2(ctrl, $scope);
;
}
function calcZins2(ctrl, $scope) {
var user = new Object;
var anpassen = false;
user = angular.copy(ctrl);
user.Berechnung;
var Row;
getZinsAnDatum(user.date2, user.fullDate2).then(function (resu) {
// Code depending on result
var value = parseFloat(resu.replace(",", "."));
user.zinsJetz = value;
Row.zinsJetz=user.zinsJetz;
user.Berechnung.push(Row);
nextAbschnitt(user, ctrl, $scope);
}).catch(function () {
// An error occurred
});
function nextAbschnitt(user, ctrl, $scope) {
getZinsAnDatum(date3,fullDate3).then(function (resulte) {
// Code depending on result
var value = parseFloat(resulte.replace(",", "."));
user.zinsNext = value;
getZinsAnDatum(date, FullDate).then(function (result) {
// Code depending on result
var value3 = parseFloat(result.replace(",", "."));
user.zinsJetz = value3;
gO(user, ctrl, $scope);
}).catch(function () {
// An error occurred
});
}).catch(function () {
// An error occurred
});
}
}
function getMonthsDifference(date1, date2) {
var k = date1.getYear() * 12 + date1.getMonth();
console.log(k + "k")
var m2 = date2.getYear() * 12 + date2.getMonth();
console.log(m2 + "m2")
return (m2 - k + 1);
}
function gO(user, ctrl, $scope) {
var g = getMonthsDifference(user.date2 user.date3);
user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum = g;
var count = 0;
var promiseFor = Promise.method(function (condition, action, value) {
if (!condition(value))
return value;
return action(value).then(promiseFor.bind(null, condition, action));
});
promiseFor(function (count) {
return count < user.AnzahlAnMonatenZwischenErsterAnpassungUndAktuellemDatum;
}, function (count) {
// ctrl.Berechnung = user.Berechnung;
return getZinsAnDatum(date3, fullDate3 ).then(function (resulte) {
// DO STUFF
ctrl.done = true; // Shows THE HTML div via ng-Show
ctrl.Berechnung = user.Berechnung;
return ++count;
});
}, 0).then(function (user) {
});
}
});
HTML:
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr><td>Zinssatz nach richtiger Anpassung:</td><td> {{ctrl.zinssatzKorrekt}}</td></tr>
<tr><td>Aktueller Zinssatz der Bank</td><td>{{ctrl.zinssatzAktuell}}</td></tr>
<tr><td>Differenz: </td><td>{{ctrl.zinssatzAktuell-ctrl.zinssatzKorrekt}}</td></tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr>
<tr> </tr> <tr> </tr>
<tr>
<td>FIBOR/EURIBOR-Stichtag</td><td>maßgeblicher FIBOR/EURIBOR in %</td><td>FIBOR/EURIBOR-
Veränderung</td> <td>Veränderung
kumuliert</td> <td>Anpassung</td> <td>gebotene
Anpassung</td> <td>Zinssatz korrekt</td></tr>
<tr ng-class="Texttype" ng-repeat="row in ctrl.Berechnung track by $index">
<td> {{row.anpDat}}</td><td>{{row.zinsJetz}} </td><td>{{row.zinsDiff}} </td> <td>{{row.veranderungKummuliert}} </td> <td>{{row.anpassen}} </td> <td>{{row.geboteneAnpassung}} </td> <td>{{row.zinssatzKorrekt}} </td></tr>
</table>

Related

jQuery Script: I Populate An Array But Can't Access It From Outside

I'm starting to fiddle with jquery and I'm going kind of crazy... I am making a little script to fetch football players from a fantasy football website. I have the following html and JS to work with:
<table class="table table-striped">
<thead>
<tr>
<th>Jugador</th>
<th>Equipo</th>
<th>Puntos</th>
</tr>
</thead>
<tbody>
<tr class="jugador">
<td>Sergio-Ramos</td>
<td>Real Madrid</td>
<td></td>
</tr>
<tr class="jugador">
<td>Messi</td>
<td>F.C. Barcelona</td>
<td></td>
</tr>
<tr class="jugador">
<td>Morales</td>
<td>Levante</td>
<td></td>
</tr>
<tr class="jugador">
<td>Bale</td>
<td>Real Madrid</td>
<td></td>
</tr>
</tbody>
</table>
And the following JS:
<script>
var puntos_jugador = [];
$(".jugador").each(function(index) {
var nombre = $(this).find("td").eq(0).text();
puntos_jugador = puntosJugador(nombre);
console.log(nombre);
console.log(puntos_jugador);
$(this).find("td").eq(2).text("Hola");
});
function puntosJugador(nombre) {
var puntos = [];
$.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {
$(response).find('.tr-points, .tr-status').each(function(fila) {
//var jornada = $(this).find("td").eq(0).text();
var puntos_jornada = $(this).find(".bar").text();
puntos.push(puntos_jornada);
//console.log('Jornada ' + jornada + ' ' + puntos);
});
});
return puntos;
}
</script>
The thing is the console.log(puntos_jugador) does return an array filled with the information:
However I cannot access puntos_jugador[0] or try puntos_jugador.toString() .
Could anyone tell me what am I doing wrong (maybe everything) or give me some orientation on how to fix this?
Thanks on beforehand and sorry for my low JS level, I'm working on it.
The problem in your code is that you are doing an asynchronous call with $.get and then you return the result directly without waiting for the response, which will always be the empty array define above.
You should wait for the response and then call a callback (or use promises)
Something like this:
var puntos_jugador = [];
$(".jugador").each(function(index) {
var nombre = $(this).find("td").eq(0).text();
puntosJugador(nombre, function(result) {
console.log('done');
puntos_jugador = result;
console.log(nombre);
console.log(puntos_jugador);
});
$(this).find("td").eq(2).text("Hola");
});
// <---- HERE pass a callback and then call it when you have all results.
function puntosJugador(nombre, cb) {
var puntos = [];
$.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {
console.log('response ',response)
$(response).find('.tr-points, .tr-status').each(function(fila) {
//var jornada = $(this).find("td").eq(0).text();
var puntos_jornada = $(this).find(".bar").text();
puntos.push(puntos_jornada);
//console.log('Jornada ' + jornada + ' ' + puntos);
console.log('here', puntos);
});
cb(puntos);
});
}
Refactor your method to this:
function puntosJugador(nombre) {
var puntos = [];
$.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {
$(response).find('.tr-points, .tr-status').each(function(fila) {
//var jornada = $(this).find("td").eq(0).text();
var puntos_jornada = $(this).find(".bar").text();
puntos.push(puntos_jornada);
//console.log('Jornada ' + jornada + ' ' + puntos);
});
return puntos;
});
}

AngularJS 1 - How to pass app.js list of values to controller.js

This is regarding Angular JS One, so I created a simple app in my plunkr.
What I did? , I created a factory called app.js and a myController.js.
The problem is the Get Method from controller.js, i dont know how to write it properly so it will pass the list of data to the html. Please check on methods getData(app.js)and Get(controller.js). What are the mistakes?
Note : Add and Edit are working fine using these three layers (app->controller->view) that i need.
PS: I tried nothing yet.
Thanks!!!
John
Below is my app.js or business
angular.module('myFirstApp',['ngRoute'])
.config(function($routeProvider){
$routeProvider
.when('/home',{templateUrl : 'home.html'})
.when('/people',{templateUrl : 'people.html'})
.when('/about',{templateUrl : 'about.html'})
.when('/contact',{templateUrl : 'contact.html'})
})
.factory('personFactory',function(){
function getData(){
$http.get('iphone.json').success(function(result){
return result;
}).error(function(error){
alert(error.error + "/" + error.statusCode);
});
}
function insertData(Name,Email,Password,Mobile){
//update data to database
var x = "Record added successfuly.";
return x;
}
function updateData(){
//update data to database
var x = "Record updated successfuly.";
return x;
}
return {
getData : getData,
insertData,
updateData
};
})
Below is my controller.js
angular.module('myFirstApp')
.controller('myController',function($scope,$http,personFactory){
$scope.Add = function(){
var x = personFactory.insertData($scope.Name,$scope.Email,$scope.Password,$scope.Mobile,$scope.result);
$scope.Message = x;
return $scope.Message;
}
$scope.Edit = function(){
var x = personFactory.updateData();
$scope.Message = x;
return $scope.Message;
}
$scope.Get = function(){
var x = personFactory.getData();
$scope.PeopleList = x;
return $scope.PeopleList;
}
})
Below is my view
<html>
<head>
<title></title>
<script src="app.js"></script>
</head>
<body>
<p>People</p>
<table ng-controller='myController'>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Model</th>
<th>Status</th>
<th>Purchased on</th>
</tr>
</thead>
<tr ng-repeat="values in PeopleList">
<td>{{values.name}}</td>
<td>{{values.email}}</td>
<td>{{values.model}}</td>
<td>{{values.status}}</td>
<td>{{values.purchasedate}}</td>
</tr>
</table>
</body>
</html>
The factory needs to return a JS Object that encapsulate all the functionalities, like this
// Data factory
app.factory("Data", function () {
return {
add: function () {
// add logic here
},
get: function () {
// get logic here
}
}
}
I guess you're having a little problem on the $http.get('iphone.json') within the factory. Maybe you should try to use a callback to handle that, like this:
app.js:
function getData(callback) {
$http.get('iphone.json').success(function(result){
callback(result);
}).error(function(error){
alert(error.error + "/" + error.statusCode);
});
}
controller.js:
$scope.Get = function(){
personFactory.getData(function(result) {
$scope.PeopleList = result;
});
}

AngularJS ng-init not working with ng-repeat

I've been trying to call passID() function when page initializes but the function still doesn't work.
The website works this way:
Page-A passes data to Controller-A
then to Service then to Controller-B then the function from Controller-B gets called by Page-B.
My guess is that my error is in Page-B since I've successfully passed the data of Page-A up to Controller-B but I'm not 100% sure.
In my Page-A, I've made a button calling the function of Controller-A using ng-Click
<button class="viewDetails" ng-click="passID([1,03,07])">test button</button>
Controller-A only gets data from Page-A
angular.module('handsetExplorerModule')
.controller("compareHandsetController", ['$scope','compareHandsetService','sharedData', function($scope, compareHandsetService, sharedData) {
$scope.passID = function(id){
var arrayID = [];
arrayID = id;
sharedData.set(arrayID);
};
}]);
Service gets my JSON and is my getter and setter
angular.module('handsetExplorerModule')
.factory('compareDetailsService', ['$http','$q', function($http, $q) {
return {
getHandsetList: function(){
return $http.get("./data/compareJSON.json");
}
};
}]);
angular.module('handsetExplorerModule')
.factory('sharedData', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
Controller-B filters the JSON file to only get what I need (i used ID from Page-A to filter)
angular.module('handsetExplorerModule')
.controller("compareDetailsController", ['$scope','compareDetailsService','sharedData', function($scope, compareDetailsService, sharedData) {
$scope.data = {phones: []};
compareDetailsService.getHandsetList()
.then(
function(data){
$scope.data.phones = data.data;
},
function(error){
//todo: handle error
}
);
var getData = sharedData.get();
$scope.passID = function passID(){
var newData = [];
for(var i=0; i<$scope.data.phones.length; i++){
if($scope.data.phones[i].id == getData[0] || $scope.data.phones[i].id == getData[01] || $scope.data.phones[i].id == getData[02]){
newData.push($scope.data.phones[i]);
}
}
$scope.phoneContent = newData;
}
$scope.viewDetails = function(id){
alert(id);
}
}]);
Lastly, In my Page-B, I've called Controller-B function: <div ng-init="passID()">
to be used by ng-repeat of my Page-B:
<table id="Content" ng-repeat="x in phoneContent track by x.id">
<tr>
<td class="one">
<table>
<tr>
<td><img class="contImage" ng-src="{{x.image}}" ng-alt="{{x.name}}" /></td>
<td class="textAlign">{{x.name}} <button class="viewDetails" ng-click="viewDetails(x.id)">VIEW DETAILS</button></td>
</table>
</td>
<td class="two">{{x.size}}</td>
<td class="one">{{x.storage}}</td>
<td class="two">{{x.camera}}</td>
<td class="one">{{x.battery}}</td>
<td class="two">{{x.network}}</td>
<td class="one">{{x.sim}}</td>
</tr>
</table>
I don't know why you define arrayID.
To solve your problem try with sharedData.set = arrayID; instead of sharedData.set(arrayID);.
Hope it helps!

AngularJS select items not resetting to first / default value

I'm at my wits end! In angular I've got a controller and a view.
There are 2 dropdowns on the page which need to reset to default once the restart button has been clicked.
I can set the value of the boxes as they render by pushing a "select" option into the collection inside the controller. However, when the reset button is pressed, which runs the init() method again, the dropdowns should be set back to the first value. This doesn't occur, the values for $scope.selectedYear and $scope.selectedReport remain as they did before the reset button was pressed.
This is the full code for the controller
function TreeReportsCHLController($scope, $q, $routeParams, reportsDashboardResource, navigationService, notificationsService, dialogService, entriesManageDashboardResource, $timeout) {
// Methods
var generalError = function () {
notificationsService.error("Ooops", "There was an error fetching the data");
$scope.actionInProgress = false;
}
// Scope
$scope.selectedYear = "";
$scope.init = function () {
$scope.hasCompleted = false;
$scope.actionInProgress = false;
$scope.yearSelected = false;
$scope.reportTypes = ["Choose", "Entered", "ShortListed", "Winner", "Recieved"];
$scope.selectedReport = "";
$scope.entryYears = new Array();
$scope.entryYears.push("Choose a Year");
entriesManageDashboardResource.getEntryYears().then(function (response) {
angular.forEach(response, function (value, key) {
$scope.entryYears.push(value);
});
});
$scope.selectedYear = $scope.entryYears[0];
$scope.selectedReport = $scope.reportTypes[0];
};
$scope.yearHasSelected = function(selectedYear) {
$scope.yearSelected = true;
$scope.selectedYear = selectedYear;
};
$scope.generateFile = function (selectedReport) {
$scope.actionInProgress = true;
var reportDetail = {
entryYear: $scope.selectedYear,
chosenEntryStatus: selectedReport
};
reportsDashboardResource.generateEntriesReportDownloadLink(reportDetail).then(function (response) {
if (response.Successful) {
$scope.hasCompleted = true;
} else {
notificationsService.error("Ooops", response.ErrorMessage);
}
$scope.actionInProgress = false;
}, generalError);
};
$scope.restart = function () {
$scope.init();
}
// Initialise Page
$scope.init();
}
angular.module("umbraco").controller("ReportsDashboardController", TreeReportsCHLController)
this is the code with the dropdowns in it;
<table>
<tr>
<td>Get a report for year: {{selectedYear}}</td>
<td><select ng-model="selectedYear" ng-change="yearHasSelected(selectedYear)" ng-options="year for year in entryYears" no-dirty-check></select></td>
</tr>
<tr ng-show="!hasCompleted && yearSelected">
<td>
Get Report Type:
</td>
<td>
<select ng-model="selectedReport" ng-change="generateFile(selectedReport)" ng-options="status for status in reportTypes" no-dirty-check ng-disabled="actionInProgress"></select>
</td>
</tr>
</table>
I've also done a further test where I simply set $scope.selectedYear to $scope.entryYears[0] within the reset method. When I console.log $scope.selectedYear here, the value confirms it has been changed, but strangely where I've outputted the $scope.selectedYear / {{selectedYear}} to the page for testing, this does not update. It's almost as though the binding between the controller and the view isn't occuring.
Any help?
Thank-you.
Here's a working plunk that is somewhat stripped down since I didn't have access to of the services that your are injecting into your controller. The changes I made in the controller are:
First,
$scope.entryYears = new Array();
becomes
$scope.entryYears = [];
as this is the preferred way to declare an array in js.
Second, I removed $scope.apply() that was wrapping
$scope.selectedYear = $scope.entryYears[0];
$scope.selectedReport = $scope.reportTypes[0];
as this was causing infinite digest cycles.

ng-change only triggers once inside a ng-repeat -- Angular

I am connecting to the Yahoo weather service API and made a little simple weather app using Angular. I also created a F - C temperature converter that triggers with the help of ng-change(). However for some reason this only works once on initialization.
For some reason I can not make sense why ng-repeat would only fire once inside an ng-repeat. Please see code below. Any help would be appreciated.
***I should mentioned that when I placed a "debugger" inside my function called, changedTemperatureTo, it triggers the "debugger" when I convert from F->C, but the "debugger" doesn't even trigger from C->F, the second time round. By second time around, I mean after I flipped the radio button from F->C the first time. When I flip it back, nothing happens - Debugger doesn't trigger.
VIEW:
{{date}}
<span ng-repeat="temp in temperatureNames">
<input type="radio" name="selectedTemperatureNamed" ng-model="selectedTemperatureName" ng-value="temp" ng-change="changedTemperatureTo(temp)"/> {{temp}}
</span>
<select ng-model="sort">
<option value="cityNameForForecast(td)">City</option>
<option value="high">High</option>
<option value="low">Low</option>
</select>
<input type="checkbox" ng-model="reverse"/> <small>*Check to Reverse Order</small>
<div ><br>
<table class="tg">
<thead>
<tr >
<th class="tg-031e"></th>
<th class="tg-031e"></th>
<th class="tg-031e"></th>
<th class="tg-031e">High</th>
<th class="tg-031e">Low</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="td in forecastAll | orderBy:sort:reverse">
<th class="tg-031e">{{cityNameForForecast(td)}}</th>
<th class="tg-031e"><img src="http://l.yimg.com/a/i/us/we/52/{{ td.code }}.gif"></th>
<th class="tg-031e">{{td.text}}</th>
<th class="tg-031e">{{td.high}}</th>
<th class="tg-031e">{{td.low}}</th>
</tr>
</tbody>
</table>
</div>
CONTROLLER:
/*global angular */
var weatherControllers = (function () {
var weatherControllers = angular.module('weatherControllers', []);
// Declare the application controller and inject the scope reference.
weatherControllers.controller('AppCtrl', ['$scope', function ($scope) {
// Define the title model.
$scope.title = "AngularJS Tutorial - Yahoo Weather App";
}]);
// Inject the scope and new weatherService reference into the controller.
weatherControllers.controller('ListCtrl', ['$scope', 'weatherService', function ($scope, weatherService) {
// Define the forecast data.
}]);
// Inject the scope and new weatherService reference into the controller.
weatherControllers.controller('WeatherCtrl', ['$scope', 'weatherService',
function ($scope, weatherService) {
// Define the forecast data.
// forcastOne >
weatherService.getWeather('Vancouver').success(function (data) {
$scope.forecastVan = weatherService.getForecastFromData(data);
console.log("forecastVan");
console.log($scope.forecastVan);
// console.log($scope.forecastVan[0]);
// console.log("$scope.forecastVan[0]['date']");
// console.log($scope.forecastVan[0]['date']);
$scope.forecastDate = $scope.forecastVan[0]['date'];
weatherService.getWeather('Honolulu').success(function (data) {
$scope.forecastHon = weatherService.getForecastFromData(data);
console.log("forecastHon");
console.log($scope.forecastHon);
console.log($scope.forecastHon[0]);
weatherService.getWeather('San Diego').success(function (data) {
$scope.forecastSan = weatherService.getForecastFromData(data);
console.log("forecastSan");
console.log($scope.forecastSan);
console.log($scope.forecastSan[0]);
weatherService.getWeather('Havana Cuba').success(function (data) {
$scope.forecastHav = weatherService.getForecastFromData(data);
console.log("forecastHav");
console.log($scope.forecastHav);
console.log($scope.forecastHav[0]);
// Create index model
$scope.forecastAll = [$scope.forecastVan[0], $scope.forecastHon[0], $scope.forecastSan[0], $scope.forecastHav[0]]
});
});
});
});
$scope.cityNameForForecast = function (forecast) {
if ($scope.forecastVan[0] == forecast) {
return 'Vancouver';
}
else if ($scope.forecastHon[0] == forecast) {
return 'Honolulu';
}
else if ($scope.forecastSan[0] == forecast) {
return 'San Diego';
}
else if ($scope.forecastHav[0] == forecast) {
return 'Havana Cuba';
}
};
// Temperature
$scope.temperatureNames = ['C', 'F'];
$scope.selectedTemperatureName = $scope.temperatureNames[1];
$scope.changedTemperatureTo = function (temperatureName) {
// debugger;
if (temperatureName == 'C') {
$scope.forecastAll = weatherService.arrayToCelsius($scope.forecastAll);
}
else if (temperatureName == 'F') {
$scope.forecastAll;
}
};
}]);
// Inject scope, $routeParams, and cardService
weatherControllers.controller('DetailCtrl', ['$scope', '$routeParams', 'weatherService',
function ($scope, $routeParams, weatherService) {
weatherService.getWeather($scope, $routeParams.cityID);
$scope.cityName = $routeParams.cityName;
weatherService.getWeather($routeParams.cityName).success(function (data) {
$scope.forecast = weatherService.getForecastFromData(data);
});
$scope.temperatureNames = ['C', 'F'];
$scope.selectedTemperatureName = $scope.temperatureNames[1];
}]);
return weatherControllers;
}());
SERVICES:
weatherApp.factory("weatherService", function ($http) {
'use strict';
return {
doSomething: function ($scope) {
},
getWeather: function (city) {
var url = this.getUrlForCity(city);
return $http.get(url);
},
getUrlForCity: function (city) {
// Weather codes:
var weatherCodes = {'Vancouver': 'CAXX0518', 'Honolulu': 'USHI0026', 'San Diego': 'USCA0982', 'Havana Cuba': 'CUXX0003'}
var city = weatherCodes[city] // Now on can call all cities at once
var yahooAPI = "'http://weather.yahooapis.com/forecastrss?p=";
var format = "'&format=json&diagnostics=true&callback=";
var yql = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D";
var url = yql + yahooAPI+ city + format;
return url;
},
getForecastFromData: function (data) {
try {
var stringified = JSON.stringify(data); // Convert to a string.
stringified = stringified.split("\\n").join(""); // Remove new line '/n'.
var listing = JSON.parse(stringified); // Convert to object.
var forecast = []; // Store 5 day forecast.
var forecastDate = []; // Stores forecast date
for (var result in listing) {
for (var item in listing[result].results) {
for (var day in listing[result].results.item.forecast) {
forecast.push(listing[result].results.item.forecast[day]);
}
}
}
}
catch (error) {
alert("Weather reading error:" + error.name + ": "
+ error.message);
}
return forecast;
},
arrayToCelsius: function (forecastArray) {
for (var i = 0; i < forecastArray.length; i++) {
forecastArray[i]['high'] = this.getCelsius(forecastArray[i]['high']);
forecastArray[i]['low'] = this.getCelsius(forecastArray[i]['low']);
}
return forecastArray;
},
getCelsius: function (fahrenheit) {
var fTempVal = this.getForecastFromData(fahrenheit);
// debugger;
// $scope.celsius = this.getForecastFromData;
var celsius = ((fahrenheit - 32) * 0.56).toFixed(0);
return celsius; // Calculation goes here.
}
}
});
From what I can see, you initially set the temperature to be in Fahrenheit.
// Temperature
$scope.temperatureNames = ['C', 'F'];
$scope.selectedTemperatureName = $scope.temperatureNames[1];
The issue happens here:
$scope.changedTemperatureTo = function(temperatureName) {
// debugger;
if (temperatureName == 'C') {
$scope.forecastAll = weatherService.arrayToCelsius($scope.forecastAll);
} else if (temperatureName == 'F') {
/*
You aren't doing anything to the forcastAll variable when the temperature
is F
*/
$scope.forecastAll;
}
};
Nothing is happening when the temperatureName == 'F'. So it'll convert from Farenheight to Celcius, but then nothing happens when going back.
Hope this helps!

Categories

Resources