2016-05-06 10 views
2

私はコード初心者で、anglejsを学ぼうとしています。私のプロジェクトは単純です:JSONデータをAPIから取得し、Webページに表示します。私は、httpリクエストを作成し、そのデータを使用する機能が見つかりました:anglejsコントローラでhttpリクエストからのデータを使用するには?

app.factory('myService', function($http) { 
    var myService = { 
    async: function() { 
     var promise = $http.get('<URL to api>').then(function(response) { 
     console.log(response); 
     return response.data; 
     }); 
     return promise; 
    } 
    }; 

    return myService; 
}); 

app.controller('getRealTimeBusDataCtrl', function(myService, $scope) { 

    myService.async().then(function(d) { 
    $scope.data = d; 
    }); 
}); 

私は、全体のJSONデータチャンクまたはその一部にアクセスして表示することができます。

私がしたいのは、1つではなく複数の$ scope変数を設定することですが、それを試みるとすぐにコードが壊れます。私は何をしようとしている

:それはどういうわけか、私は私を設定したり、多くのことができ、変数の数を制限していること:私はこの問題を推測している

if (d.ResponseData.Buses[1].JourneyDirection = 1) { 
    $scope.timeToSollentuna = d.ResponseData.Buses[1].DisplayTime; 
    else if (d.ResponseData.Buses[1].JourneyDirection = 2) { 
    $scope.timeToVallingby = d.ResponseData.Buses[1].DisplayTime; 
    } else if (d.ResponseData.Buses[2].JourneyDirection = 1) { 
    $scope.timeToSollentuna = d.ResponseData.Buses[2].DisplayTime; 
    } else { 
    $scope.timeToVallingby = d.ResponseData.Buses[2].DisplayTime; 
    } 
} 

は機能が設定されている方法です私はそれをやるために別の方法を考え出すことができませんでした。

申し訳ありませんが、この質問への答えは明らかですが、私は本当にそれを見つけようとしましたが失敗しました。

敬具、

+4

if文を使用する場合は、シングル( '=')ではなく、ダブルまたはトリプルの等価( '=='、 '===')を使用します。参照してください:http://stackoverflow.com/questions/523643/difference-between-and-in-javascript – Kyle

+0

'コードが壊れているときにどんなエラーが発生していますか? – Shaffanhoon

+0

=と==、===の使用を指摘してくれてありがとう! –

答えて

0

サービスが書かれている方法は、不必要に冗長です。代わりに、私はこれを書き直してみましょう(特に出発して基礎を学ぶなら、起動時に良い習慣を学ぶのが良いです)。

app.factory('myService', ["$http", function($http){ 
    return { 
     getData: function() { 
      return $http.get('path/to/api'); 
     } 
    }; 
}]); 

app.controller('MainCtrl', ["$scope", "myService", function($scope, myService) { 
    //declare your data model first 
    $scope.busData = undefined; 

    //use the service to get data 
    myService.getData().then(function(response) { 
     //success... got a response 
     //this is where you can apply your data 
     $scope.busData = response.data; 

     //call a function to apply if you'd like 
     applyBusData(response.data); 
    }).catch(function(response) { 
     //error has occurred 
    }); 

    function applyBusData(data) { 
     if(data.Buses[1].JourneyDirection === 1) { 
      //etcc... etc... 
     } else { 
      //etc.. etc... 
     } 
    } 
}]); 
+0

ありがとうございました!私はそれが今働いている:) –

関連する問題