2016-06-30 3 views
1

Ich erhalte Daten von einer Remote-Anforderung von companiesData.getCompanies() und setze sie in die Controller-Variable.Controller-Variable asynchron Wert zuweisen - AngularJS

Der Controller wartet nicht auf die Auflösung des Versprechens und stellt fest, dass das Antwortfeld leer ist.

JS Controller:

angular.module('X.Exh', []) 

.controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) { 

    this.companies = []; 

    companiesData.getCompanies().then(function(response) { 
     this.companies = response.data; 
console.log(this.companies); // working very well 
    }); 
}); 

HTML:

<ion-alpha-scroll ng-model="Exh.companies" key="name" display-key="name" subheader="true" use-complete-alphabet="true"> 
<!-- Basically the ion alpha scroll is just doing a ng-repeat for every item, it is not the problem here --> 

Nicht für die HTTP-Anforderung warten, Exh.companies Zahlen leer. (Natürlich, wenn ich this.companies = []; tue nicht am Anfang meines Controller, mein HTML sagt, dass Exh.companies nicht definiert ist.

Wie bekomme ich Daten richtig?

+1

Verwenden $ scope.componies = []; –

Antwort

3

dies innerhalb der unbenannte Funktion nicht original beeinflussen this.companies :

angular 
.module('X.Exh', []) 
.controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) { 

    var vm = this; 
    vm.companies = []; // you can omit this but for documentation and code clear you can declare it; 

    companiesData.getCompanies().then(function(response) { 
     vm.companies = response.data; 
     console.log(vm.companies); // does not point to local this.companies but to the caller context. 
    }); 
}); 

Bitte Notiz dass vm. ausgeführt, wenn Sie controllerAspattern verwenden

. Alternativ

können Sie einfach $scope Variable zugreifen:

angular 
.module('X.Exh', []) 
.controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) { 

    $scope.companies = []; // you can omit this but for documentation and code clear you can declare it; 

    companiesData.getCompanies().then(function(response) { 
     $scope.companies = response.data; 
     console.log($scope.companies); // does not point to local this.companies but to the caller context. 
    }); 
}); 
+0

Vielen Dank, Sie hatten Recht! aber eigentlich habe ich var self = this; und dann self.companies. Es ist eine gute Lösung? – Doapper

+1

'var self = this;' ist das gleiche wie 'var vm = this;' also besteht die einzige Einschränkung darin, 'ng-controller =' ExhibitorsController as Exh 'zu deklarieren und auf Daten im HTML-Format wie 'Exh.myvar' zuzugreifen. Sie erreichen bereits diese zweite Lösung, die auch für große Anwendungen geeignet ist. – morels