2016-10-28 7 views
0

私は工場で工場を作り、それをコントローラで使用しようとしていますが、工場ではgetメソッドからデータを返してコントローラに保存していますが、動作していないので、$ scope.myDataはundefindを返します。コントローラanglejsでの工場の使い方

var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope, myService) { 
    $scope.myData = myService.getEvent(); 
}); 
app.factory('myService', function($http){ 
    var oGetData = {}; 
    oGetData.getEvent = function(){ 
     $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival') 
     .then(function(response) { 
     return response.data.event; 
     }); 
    }; 

    return oGetData ; 
}); 

私はコントローラに直接その作業罰金を工場出荷時のコードを使用し

var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope, $http) { 
    $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival') 
     .then(function(response) { 
      $scope.myData = response.data.event; 
     }); 
}); 

誰かが私が最初のコードで間違ってください何をしたか私に言うことができますか? http://codepen.io/jdoyle/pen/KgLjgY

これは、よく寄せられる質問です:

はここcodepen http://codepen.io/anon/pen/NRVZdE

答えて

1

ワーキングCodepenです。あなたは、これは、データを返すように期待しているが、それはしていません:

app.controller('myCtrl', function($scope, myService) { 
    $scope.myData = myService.getEvent(); 
}); 

getEvent()は約束ではなく、データを返します。変更したい場合は

oGetData.getEvent = function(){ 
    return $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival'); 
}; 

app.controller('myCtrl', function($scope, myService) { 
    myService.getEvent().then(function(response){ 
     $scope.myData = response.data.event; 
    }); 
}); 

そして、あなたの工場内だけで$httpと他には何にコールを返す:$httpへの呼び出しがでしょうあなただけのようなリターン・オブジェクトを処理する必要がありますデータをコントローラに戻す前に、独自の遅延を作成して、次のように自分で応答を処理することができます。

oGetData.getEvent = function(){ 
    var deferred = $q.defer(); 
    $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival') 
    .then(function(response) { 
     deferred.resolve(response.data.event); 
    }); 
    return deferred.promise; 
}; 

応答データからイベントを心配する必要があります。

app.controller('myCtrl', function($scope, myService) { 
    myService.getEvent().then(function(event){ 
     $scope.myData = event; 
    }); 
}); 
+0

このコード出力誤差はTypeErrorを:それが参照しているどのライン未定義 – ahmdabos

+0

の「を」プロパティを読み取ることができませんか?あなたは、見るために羽目板またはコデペンを持っていますか? –

+0

ありがとうございました – ahmdabos

関連する問題