2016-06-30 6 views
1

companiesData.getCompanies()によってリモートリクエストからデータを取得し、それをコントローラ変数に入れます。コントローラ変数asyncronouslyに値を代入 - AngularJS

コントローラーは、応答アレイが空であると考えて、約束の解像度を待つことはありません。

JSコントローラ:

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 --> 

Exh.companiesフィギュア空、HTTPリクエストを待っていません。 (もちろん、私は私のコントローラの先頭にthis.companies = [];をしない場合は、私のHTMLはExh.companiesが未定義であることを述べている。

がどのように私は無名の関数内?

+1

使用$ scope.componies = []; –

答えて

3

これは、元の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. 
    }); 
}); 

くださいノートvm.その実行をおcontrollerAspatternを使用

はまたあなたは、単にアクセスすることができ$scope変数:

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

大変ありがとうございました!実際に私はvar self = thisを使用しました。それからself.companies。それは良い解決策ですか? – Doapper

+1

'var self = this;'は 'var vm = this;'と同じですので、 'ng-controller = 'ExhibitorsControllerをExhとして宣言し、' Exh.myvar'のようにhtmlのデータにアクセスしてください。あなたは既に大規模なアプリケーションのベストプラクティスであるこの2番目のソリューションを達成しています。 – morels

関連する問題