AngularJS resource with JSONP

Lately I struggled to get access to facebook by JSONP. I try to do it in AngularJS with factory and resource. I want to share with people my solution. Let's try to connect to the Facebook Graph. Firstly, we create index.html file with input graph.username, after type a value there is called getGraph(). The result of the calling this function is saved in $scope.result so we can display it. <html ng-app="myApp"> <head> <title>AngularJS resource with JSONP</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"/> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-resource.min.js"/> <script type="text/javascript" src="app.js"/> </head> <body> <div ng-controller="MyController"> Graph for: <input type="text" ng-model="graph.username" ng-blur="getGraph()"> <h3>{{result.name}}</h3> <div>{{result.about}}</div> </div> </body> </html> Secondly, in app.js we write controller and factory which creates a resource object that call the Facebook Graph. So when it is called function getGraph we use GraphFacebook factory to call getJSONP passing in argument $scope.graph with username property. This property is used in building URL.
var myApp = angular.module('myApp', ['myServices']);

myApp.controller('MyController', ['$scope', 'GraphFacebook', 
  function($scope, GraphFacebook) {
    $scope.getGraph = function() {
      $scope.result = GraphFacebook.getJSONP($scope.graph);
    };
}]);

var myServices = angular.module('myServices', ['ngResource']);

myServices.factory('GraphFacebook', ['$resource',
  function($resource) {
    return $resource('https://graph.facebook.com/:username', {}, {
      getJSONP: {
        method: 'JSONP',
        params: {
          callback: 'JSON_CALLBACK'
        }
      }
    });
  }
]);

The result of our work:


Source on GitHub

Komentarze

Popularne posty z tego bloga

AngularJS example MotoAds more advanced than the tutorial on angularjs.org

Java ESL program for connecting to the FreeSWITCH

Java program for connecting to the FreeSWITCH XML-RPC