LoginSignup
24
24

More than 5 years have passed since last update.

AngularJSアプリからJSONP呼出を利用する(v1.0.2 )

Last updated at Posted at 2012-11-13

外部リソースをJSONPで読み込む為だけにjQueryとか追加しようとしていたけれど(※AnglarJSが内包しているjQLiteは最低限のjQuery APIを提供するもの。DOMセレクタなどもない)、
コントローラーに$httpモジュールを渡して呼び出せばいいらしい。

コールバック関数にJSON_CALLBACKの定数っぽい文字列を渡すとよしなに処理してくれる。

Demo: http://jsfiddle.net/laiso/RvDNU/
Reference: http://docs.angularjs.org/api/ng.$http#jsonp

app.js
function LoctouchAPI($http){
    this.loadStations = function(callback){
        $http.jsonp('https://api.loctouch.com/v1/railway/stations?line_cd=11302&callback=JSON_CALLBACK')
            .success(function(response){
                callback(response.stations);
            });
    };
}

function AppController($scope, $http){
    $scope.stations = [];

    $scope.onLoadButton = function(){
        var api = new LoctouchAPI($http);
        api.loadStations(function(stations){
            $scope.stations = stations;
        });
    };

    $scope.clear = function(){
        $scope.stations = [];
    };

    $scope.jsonDump = function(json){
        return JSON.stringify(json);
    };
}
24
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
24