//declaring the module
var app = angular.module("sachin", ["ng-fusioncharts"]);
//declaring a factory
app.factory('team',function(){
return {
runs_aus : ''
};
});
app.controller("myCtrl", function($scope,$http,team){
$scope.australia=[];
$scope.total_runs_aus=0;
//fetching data from JSON
$http.get("convertcsv.json").then(function(response){
$scope.sachin_data=response.data;
angular.forEach($scope.sachin_data, function(value, key){
// manipulating data
if (value.opposition=="v Australia"){
if (value.batting_score=="-"|| value.batting_score == "TDNB" || value.batting_score == "DNB")
$scope.total_runs=$scope.total_runs;
else if (value.batting_score.substr(value.batting_score.length - 1) == "*"){
value.batting_score = value.batting_score.substr(1);
$scope.total_runs_aus+=parseInt(value.batting_score,10)
}
else
$scope.total_runs_aus+=parseInt(value.batting_score,10);
});
$scope.australia.push({ runs:$scope.total_runs_aus});
team.runs_aus=$scope.total_runs_aus;
//got final result in $scope.total_runs_aus
console.log(team.runs_aus);
//printing inside the scope(works fine)
});
console.log(team.runs_aus);
//printing outside the scope(can't access)
Ich versuche, die Gesamtdurchläufe außerhalb des hat den Zugriff dann (function()) des Erhaltungs-Anforderungs-Wie kann ich in Angular JS auf meine Daten außerhalb bestimmter Bereiche zugreifen?
Zuerst versuchte ich globale Variablen in Javascript
Jetzt habe ich versucht, Verwenden einer Fabrik Jegliche Hilfe wäre willkommen
Sie arbeiten mit asynchronen Daten. Verschieben Sie die Logik, die die Variable totalRuns verwendet, ebenfalls in die Funktion then(). Die Konsolenprotokolle werden ausgeführt, bevor das Versprechen aufgelöst wird, sodass die Daten nicht verfügbar sind. – Gregg
Erwägen Sie die Verwendung von Versprechensketten, wenn Sie möchten, dass ein bestimmter Code ausgeführt wird, nachdem die Anforderung '$ http.get' aufgelöst wurde. Siehe ein Beispiel: http://Stackoverflow.com/a/24360864/5304361 – Gregg
Verstehst du, was ich vorschlagen? Verschieben Sie beispielsweise Ihre Konsolenprotokolle unter den Block 'if else' innerhalb der Funktion .then(). Der Code innerhalb der then() wird ausgeführt, wenn '$ http.get()' fertig ausgeführt ist. Angesichts der Position Ihrer Konsolenprotokolle werden diese ausgeführt, bevor die Daten verfügbar sind. – Gregg