How to add twitter feed in AngularJS / Ionic apps for android - angularjs

I have used sample code to add twitter feed in my apps from following link
https://github.com/bradleyprice/ionic_twitterfeed but I got token null, so nothing to show in my app just refreshing screen.After that i refer blog http://blog.ionic.io/displaying-the-twitter-feed-within-your-ionic-app/ it also give me same result.
Please suggest me changes or any another link where i get best solution.
Some code are shown as follows , in index.html
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/sha.js"></script>
<script src="lib/angular-resource/angular-resource.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="js/ng-cordova-oauth.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter" ng-controller="AppCtrl">
app.js
angular.module('starter', ['ionic', 'ngResource', 'ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
});
controllers.js
angular.module('starter').controller('AppCtrl', function($scope, $ionicPlatform, $ionicPopup, TwitterService) {
// Should we show the post tweet button
$scope.showUpdateStatus = true;
// 1
$scope.correctTimestring = function(string) {
return new Date(Date.parse(string));
};
// 2
$scope.showHomeTimeline = function() {
alert("1");
TwitterService.getHomeTimeline().then(function(res) {
alert("home_timeline");
$scope.home_timeline = res;
}, function(req) {
console.log(req);
});
};
// 3
$scope.doRefresh = function() {
$scope.showHomeTimeline();
$scope.$broadcast('scroll.refreshComplete');
};
$scope.updateStatus = function() {
TwitterService.updateStatus().then(function(res) {
$scope.showUpdateStatus = false;
$scope.doRefresh();
}, function(req) {
console.log(req);
});
}
// 4
$ionicPlatform.ready(function() {
if (TwitterService.isAuthenticated()) {
$scope.showHomeTimeline();
} else {
TwitterService.initialize().then(function(result) {
if(result === true) {
$scope.showHomeTimeline();
}
});
}
});
});
services.js
angular.module('starter',['ionic', 'ngCordovaOauth']).factory('TwitterService', function($cordovaOauth, $cordovaOauthUtility, $http, $resource, $q) {
// 1
var twitterKey = "";
var clientId = '';
var clientSecret = '';
// 2
function storeUserToken(data) {
window.localStorage.setItem(twitterKey, JSON.stringify(data));
}
function getStoredToken() {
return window.localStorage.getItem(twitterKey);
}
// 3
function createTwitterSignature(method, url) {
var token = angular.fromJson(getStoredToken());
var oauthObject = {
oauth_consumer_key: clientId,
oauth_nonce: $cordovaOauthUtility.createNonce(32),
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_token: token.oauth_token,
oauth_version: "1.0"
};
var signatureObj = $cordovaOauthUtility.createSignature(method, url, oauthObject, {}, clientSecret, token.oauth_token_secret);
$http.defaults.headers.common.Authorization = signatureObj.authorization_header;
}
function createTwitterPostSignature(method, url, message) {
var token = angular.fromJson(getStoredToken());
var oauthObject = {
oauth_consumer_key: clientId,
oauth_nonce: $cordovaOauthUtility.createNonce(32),
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_token: token.oauth_token,
oauth_version: "1.0",
status: message
};
var signatureObj = $cordovaOauthUtility.createSignature(method, url, oauthObject, oauthObject, clientSecret, token.oauth_token_secret);
$http.defaults.headers.common.Authorization = signatureObj.authorization_header;
}
return {
// 4
initialize: function() {
var deferred = $q.defer();
var token = getStoredToken();
alert(token);
if (token !== null) {
deferred.resolve(true);
} else {
$cordovaOauth.twitter(clientId, clientSecret).then(function(result) {
storeUserToken(result);
deferred.resolve(true);
}, function(error) {
deferred.reject(false);
});
}
return deferred.promise;
},
// 5
isAuthenticated: function() {
return getStoredToken() !== null;
},
// 6
getHomeTimeline: function() {
var home_tl_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
createTwitterSignature('GET', home_tl_url);
return $resource(home_tl_url).query().$promise;
},
updateStatus: function() {
var message = "test from ionic";
var update_url = 'https://api.twitter.com/1.1/statuses/update.json';
var results = createTwitterPostSignature('POST', update_url, message);
return $resource(update_url, {'status': message}).save().$promise;
},
storeUserToken: storeUserToken,
getStoredToken: getStoredToken,
createTwitterSignature: createTwitterSignature,
createTwitterPostSignature: createTwitterPostSignature
};
})

Might be worth checking out this example on Github
https://github.com/bradleyprice/ionic_twitterfeed

Related

express-angular-node: Voting Application

the following are my two files for a simple voting app and for some reason the button are not increasing the count only when you refresh the voting.html page does both count increase by one. Your help is appreciated.
<!-- voting.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Voting</title>
<script src="angular.min.js"></script>
<script>
var app = angular.module('myFirstApp', []);
app.controller('CounterCtrl', function($scope,$http) {
console.log('CounterCtrl started');
// $scope.countA = 0;
// $scope.countB = 0;
// $scope.Acrease = function() {
// console.log('Acrease() called');
// $scope.countA++;
// };
// $scope.Bcrease = function() {
// console.log('Bcrease() called');
// //if($scope.count>0) $scope.count--;$scope.count++;
// $scope.countB++;
// };
function getItemsA() {
$http.get('/voteA').then(function(res) {
$scope.countA = res.data;
//$scope.countA = res.json(A);
console.log('/voteA: ', $scope.countA);
});
}
getItemsA();
function getItemsB() {
$http.get('/voteB').then(function(res) {
$scope.countB = res.data;
//$scope.countA = res.json(A);
console.log('/voteB: ', $scope.countB);
});
}
getItemsB();
// $scope.addItem = function() {
// console.log('addItem()\t newItem=', $scope.newItem);
// $http.get('/list/add/' + $scope.newItem).then(getItems);
// };
});
</script>
</head>
<body ng-app="myFirstApp">
<div ng-controller="CounterCtrl">
<p>Count of A Vote: <b>{{countA}}</b></p>
<p>Count of B Vote: <b>{{countB}}</b></p>
<input type="button" ng-click="getItemsA()" value="A">
<input type="button" ng-click="getItemsB()" value="B">
</div>
</body>
</html>
/***server.js***/
var express = require('express');
var app = express();
app.listen(3001, function() {
console.log('Listening on 3001');
});
// Mount the public directory at /
app.use('/', express.static('./public'));
/********************************************
* This code is for voting.html
*******************************************/
// initialize the votes variables
var A = 0 ;
var B = 0 ;
// add the voteA
app.get('/voteA', function(req,res) {
//res.json(A);
A++
res.json(A);
});
// add the voteB
app.get('/voteB', function(req,res) {
//res.json(A);
B++
res.json(B);
});
This is angular1 I presume.
I think your problem is that your ng-click is calling a function which is not in scope. I believe you should create scope functions:
$scope.getItemsA = function() {
$http.get('/voteA').then(function(res) {
$scope.countA = res.data;
console.log('response recieved');
});
};
Hope it helps..

How to use Angular geolocation directive with google map ?

I am using Angular geolocation for get location. Its returning latitude and longitude of location. I want to show map using this latitude and longitude. Also want to show a circle with 5 km. take a look of my code index.html
<html>
<head>
<title>ngGeolocation</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
<script src="./ngGeolocation.js"></script>
<script src="./index.js"></script>
</head>
<body ng-app="geolocationDemo">
<div ng-controller="AppController">
<h1>Basic (fetch once)</h1>
Latitude: {{location.coords.latitude}}
<br />
Longitude: {{location.coords.longitude}}
<br />
</div>
</body>
</html>
Index.js
angular
.module('geolocationDemo', ['ngGeolocation'])
.controller('AppController', function($scope, $geolocation){
$scope.$geolocation = $geolocation
// basic usage
$geolocation.getCurrentPosition().then(function(location) {
$scope.location = location
});
// regular updates
$geolocation.watchPosition({
timeout: 60000,
maximumAge: 2,
enableHighAccuracy: true
});
$scope.coords = $geolocation.position.coords; // this is regularly updated
$scope.error = $geolocation.position.error; // this becomes truthy, and has 'code' and 'message' if an error occurs
//console.log($scope.coords);
});
ngGeolocation.js
angular
.module('ngGeolocation', [])
.factory('$geolocation', ['$rootScope', '$window', '$q', function($rootScope, $window, $q) {
function supported() {
return 'geolocation' in $window.navigator;
}
var retVal = {
getCurrentPosition: function(options) {
var deferred = $q.defer();
if(supported()) {
$window.navigator.geolocation.getCurrentPosition(
function(position) {
$rootScope.$apply(function() {
retVal.position.coords = position.coords;
deferred.resolve(position);
});
},
function(error) {
$rootScope.$apply(function() {
deferred.reject({error: error});
});
}, options);
} else {
deferred.reject({error: {
code: 2,
message: 'This web browser does not support HTML5 Geolocation'
}});
}
return deferred.promise;
},
watchPosition: function(options) {
if(supported()) {
if(!this.watchId) {
this.watchId = $window.navigator.geolocation.watchPosition(
function(position) {
$rootScope.$apply(function() {
retVal.position.coords = position.coords;
delete retVal.position.error;
$rootScope.$broadcast('$geolocation.position.changed', position);
});
},
function(error) {
$rootScope.$apply(function() {
retVal.position.error = error;
delete retVal.position.coords;
$rootScope.$broadcast('$geolocation.position.error', error);
});
}, options);
}
} else {
retVal.position = {
error: {
code: 2,
message: 'This web browser does not support HTML5 Geolocation'
}
};
}
},
position: {}
//console.log(position);
};
return retVal;
}]);
How to i can do it ? Please suggest me some solutions.
Have a look at angular-google-maps, you should be able to create the map and circle:
http://angular-ui.github.io/angular-google-maps/

Youtube iframe Api and Angularjs route

I encountered a problem with Youtube Iframe Api used with angularjs.
I think the problem is the call of "onYouTubeIframeAPIReady" function.
I use angularjs with routes and the function doesn't fire when the route is changed, however when I hit F5 it's ok the player is loaded.
Is there a way to make angularjs with routes and youtube API work?
I didn't manage to add more file in the code but "pageX.htm" looks like this :
<button ng-click="video()">Create</button>
<div youtube-player id="test-playerX" ></div>
And there is the code for "index.htm"
<!DOCTYPE html>
<html ng-app="sc">
<body>
Homepage - Page1 - Page2
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.3/angular-route.min.js"></script>
<script>
var sc = angular.module('sc', ['ngRoute']);
sc.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/page1', {
templateUrl: 'page1.htm'
})
.when('/page2', {
templateUrl: 'page2.htm'
})
}]);
// Run
sc.run(['$rootScope', function($rootScope) {
var tag = document.createElement('script');
// This is a protocol-relative URL as described here:
// http://paulirish.com/2010/the-protocol-relative-url/
// If you're testing a local page accessed via a file:/// URL, please set tag.src to
// "https://www.youtube.com/iframe_api" instead.
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}]);
sc.service('youtubePlayerApi', ['$window', '$rootScope', '$log', function ($window, $rootScope, $log) {
var service = $rootScope.$new(true);
// Youtube callback when API is ready
$window.onYouTubeIframeAPIReady = function () {
$log.info('Youtube API is ready');
service.ready = true;
service.createPlayer();
};
service.ready = false;
service.playerId = null;
service.player = null;
service.videoId = "sGPrx9bjgC8";
service.playerHeight = '390';
service.playerWidth = '640';
service.bindVideoPlayer = function (elementId) {
$log.info('Binding to player ' + elementId);
service.playerId = elementId;
};
service.createPlayer = function () {
$log.info('Creating a new Youtube player for DOM id ' + this.playerId + ' and video ' + this.videoId);
return new YT.Player(this.playerId, {
height: this.playerHeight,
width: this.playerWidth,
videoId: this.videoId
});
};
service.loadPlayer = function () {
// API ready?
if (this.ready && this.playerId && this.videoId) {
if(this.player) {
this.player.destroy();
}
this.player = this.createPlayer();
}
};
return service;
}]);
sc.directive('youtubePlayer', ['youtubePlayerApi', function (youtubePlayerApi) {
return {
restrict:'A',
link:function (scope, element) {
youtubePlayerApi.bindVideoPlayer(element[0].id);
}
};
}]);
sc.controller('replaycontroller', function ($scope,youtubePlayerApi) {
$scope.video = function () {
youtubePlayerApi.createPlayer();
console.log("test");
}
});
</script>
</body>
</html>
Any help is appreciated :)
[EDIT] : I have updated the code to test the fonction createPlayer and confirm that the player is working when changing pages
As Karan Kapoor says in the last comment, the best way to use youtube api with angularjs is to use github.com/brandly/angular-youtube-embed
OK I have found a solution, it is far not the cleanest but it works.
I admit that in the controller when you are changing routes, the youtube api is already initialized. So the controller just create the player.
When F5 or first time loading requested, we must fire onYouTubeIframeAPIReady to instantiate the player.
Here is the code :
<!DOCTYPE html>
<html ng-app="sc">
<body>
Homepage - Page1 - Page2
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.3/angular-route.min.js"></script>
<script>
var sc = angular.module('sc', ['ngRoute']);
sc.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/page1', {
templateUrl: 'page1.htm',
controller: 'replaycontroller'
})
.when('/page2', {
templateUrl: 'page2.htm'
})
}]);
// Run
sc.run(['$rootScope', function($rootScope) {
var tag = document.createElement('script');
// This is a protocol-relative URL as described here:
// http://paulirish.com/2010/the-protocol-relative-url/
// If you're testing a local page accessed via a file:/// URL, please set tag.src to
// "https://www.youtube.com/iframe_api" instead.
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}]);
sc.service('youtubePlayerApi', ['$window', '$rootScope', '$log', function ($window, $rootScope, $log) {
var service = $rootScope.$new(true);
// Youtube callback when API is ready
$window.onYouTubeIframeAPIReady = function () {
$log.info('Youtube API is ready');
service.ready = true;
service.createPlayer();
};
service.ready = false;
service.playerId = null;
service.player = null;
service.videoId = "sGPrx9bjgC8";
service.playerHeight = '390';
service.playerWidth = '640';
service.getStatus = function () {
return service.ready;
};
service.bindVideoPlayer = function (elementId) {
$log.info('Binding to player ' + elementId);
service.playerId = elementId;
};
service.createPlayer = function () {
$log.info('Creating a new Youtube player for DOM id ' + this.playerId + ' and video ' + this.videoId);
return new YT.Player(this.playerId, {
height: this.playerHeight,
width: this.playerWidth,
videoId: this.videoId
});
};
service.loadPlayer = function () {
// API ready?
if (this.ready && this.playerId && this.videoId) {
if(this.player) {
this.player.destroy();
}
this.player = this.createPlayer();
}
};
return service;
}]);
sc.directive('youtubePlayer', ['youtubePlayerApi', function (youtubePlayerApi) {
return {
restrict:'A',
link:function (scope, element) {
youtubePlayerApi.bindVideoPlayer(element[0].id);
}
};
}]);
sc.controller('replaycontroller', function ($scope,youtubePlayerApi) {
if (youtubePlayerApi.getStatus() == true) {
youtubePlayerApi.bindVideoPlayer("test-player1");
youtubePlayerApi.createPlayer();
}
});
</script>
</body>
</html>
I had the same problem and what i did was to reset the script to null and then set it again:
init() {
if (window["YT"]) {
window["YT"] = null;
this.tag = document.createElement("script");
this.tag.src = "https://www.youtube.com/iframe_api";
this.firstScriptTag = document.getElementsByTagName("script")[0];
this.firstScriptTag.parentNode.insertBefore(this.tag, this.firstScriptTag);
}
this.tag = document.createElement("script");
this.tag.src = "https://www.youtube.com/iframe_api";
this.firstScriptTag = document.getElementsByTagName("script")[0];
this.firstScriptTag.parentNode.insertBefore(this.tag, this.firstScriptTag);
window["onYouTubeIframeAPIReady"] = () => this.startVideo();
}

Integrate facebook with cordova and angular (Ionic)

I'm trying to add facebook integration to my ionic mobile app that I'm building using cordova. I'm able to get it working either without cordovaa or angular but in no way with both. With the code below, everything goes fine till FB.init gets called after loading all.js . After that, no further code is executed inside _init function, and because of that I cannot subscribe to events or do anything else.
angular facebook directive (uses code from this gist : https://gist.github.com/ruiwen/4722499)
angular.module('facebook', [])
.directive('fb', ['$FB', function($FB) {
return {
restrict: "E",
replace: true,
template: "<div id='fb-root'></div>",
compile: function(tElem, tAttrs) {
return {
post: function(scope, iElem, iAttrs, controller) {
var fbAppId = iAttrs.appId || '';
var fb_params = {
appId: iAttrs.appId || "",
cookie: iAttrs.cookie || true,
status: iAttrs.status || true,
nativeInterface: CDV.FB,
useCachedDialogs: false,
xfbml: iAttrs.xfbml || true
};
// Setup the post-load callback
window.fbAsyncInit = function() {
$FB._init(fb_params);
if('fbInit' in iAttrs) {
iAttrs.fbInit();
}
};
(function(d, s, id, fbAppId) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk', fbAppId));
}
}
}
};
}])
.factory('$FB', ['$rootScope', function($rootScope) {
var fbLoaded = false;
// Our own customisations
var _fb = {
loaded: fbLoaded,
isLoaded : function(){
return this.loaded;
},
authenticated : false,
isAuthenticated : function(){
return this.authenticated;
},
statusUpdated: function(response){
if (response.status == 'connected') {
self.authenticated = true;
alert('logged in');
} else {
alert('not logged in');
}
},
_init: function(params) {
self = this;
if(window.FB) {
// FIXME: Ugly hack to maintain both window.FB
// and our AngularJS-wrapped $FB with our customisations
angular.extend(window.FB, this);
angular.extend(this, window.FB);
// Set the flag
this.loaded = true;
// Initialise FB SDK
FB.init(params);
//THIS CODE IS NOT CALLED
FB.Event.subscribe('auth.statusChange', function(response) {
alert('auth.statusChange event');
});
FB.Event.subscribe('auth.authStatusChange', self.statusUpdated)
if(!$rootScope.$$phase) {
$rootScope.$apply();
}
}
}
}
return _fb;
}]);
My controller :
angular.module('starter.controllers', [])
.controller('StartCtrl', [
'$scope',
'$FB',
'$location',
function($scope, $FB, $location) {
$scope.$watch(function() {
return $FB.isLoaded()
},function(value){
console.log("VALUE",value);
// It needs authentication, this won't work.
if(value){
$scope.facebook_friends = $FB.api('/me/friends', function(response) {
$scope.facebook_friends = response.data;
});
}
},true);
$scope.$watch(function() {
return $FB.isAuthenticated()
},function(value){
alert("VALUE isAuthenticated "+value);
// YEP, this will work.
if(value){
$scope.facebook_friends = $FB.api('/me', function(response) {
$scope.facebook_friends = response.data;
console.log("FRIENDS",response);
});
}
},true);
$scope.FBlogin = function() {
FB.login(null, {scope: 'email'});
};
}
])
index.html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=0.5, maximum-scale=0.5, user-scalable=no, width=device-width">
<title>Starter</title>
<link href="lib/css/ionic.css" rel="stylesheet">
<link href="css/app.css" rel="stylesheet">
<script src="lib/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/angular-fb.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<!-- cordova facebook plugin -->
<script src="cdv-plugin-fb-connect.js"></script>
<!-- facebook js sdk -->
<script src="facebook-js-sdk.js"></script>
</head>
<body ng-app="starter" animation="slide-left-right-ios7">
<ion-nav-view></ion-nav-view>
<fb app-id='appid'></fb>
</body>
</html>
and app.js
angular.module('starter', ['ionic', 'starter.services', 'starter.controllers', 'facebook'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('start', {
url: "/start",
templateUrl: "templates/start.html",
controller: 'StartCtrl'
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/start');
});
You should not doing this <script src="facebook-js-sdk.js"></script> actually since it against TOS. Even-though you want to make sure the sdk is loading.
Instead you can try this code below (to make sure you can install cordova-inappbrowser first)
<script>
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '{your-app-id}',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.5' // use graph api version 2.5
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
To deeper insight
1 first add this plugin
cordova plugin add cordova-plugin-inappbrowser
2 After that create app id follow these steps
https://developers.facebook.com/docs/apps/register
3 After that add this code where you need facebook integration`
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$cordovaOauth.facebook("447073565475718", ["email", "public_profile"]).then(function(result) {
displayData($http, result.access_token);
var name = result.data.name;
var gender = result.data.gender;
var location = result.data.location;
var picture = result.data.picture;
}, function(error) {
console.log(error);
});
};
function displayData($http, access_token)
{
$http.get("https://graph.facebook.com/v2.2/me", {params: {access_token: access_token, fields: "name,gender,location,picture,email", format: "json" }}).then(function(result)
{
console.log(JSON.stringify(result));
var name = result.data.name;
var gender = result.data.gender;
var location = result.data.location;
var picture = result.data.picture;
var id =result.data.id;
var userid=id;
}, function(error) {
alert("There was a problem getting your profile. Check the logs for details.");
console.log(error);
});
`
une ngcordova, it gives you simple AngularJS wrappers for a massive amount of Cordova plugins, it include a wrapper for facebookConnectPlugin
The phonegap-facebook-plugin version 0.8.1 has more to do than a simple installation via cordova plugin add. phonegap-native-fb-ionic mentions the required one for ionic step by step.
You should integrate with Facebook through the facebookConnectPlugin of cordova.
You will find a deep explanation of how to use it in this link: https://github.com/Wizcorp/phonegap-facebook-plugin.
The plugin gives you everything you need and short examples. But you have to make sure the following things will be done:
Read carefully the instructions of installing the plugin. I choosed the manual way to install the plugin for Android through the cordova CLI.
Remember that you can use all phonegap plugins only after the deviceReady event, so you have to make sure you are calling the api of the facebookConnectPlugin after the device is ready of course.
Good luck!

Phonegap.js on second html page

I basically have two pages in my phonegap application that I am building with PGB (index.html and main.html), that both use angular.js. Index.html is a login for the app, which redirects to main.html afterwards. All my plugins and phonegap.js are being injected fine into main, but none of the inline JS (alerts on doc ready, device ready, window load) are firing, let alone phonegap.js being loaded as well.
Any advice would be appreciated.
Script Includes:
<script src="phonegap.js"></script>
<script src="cdv-plugin-fb-connect.js"></script>
<script src="facebook-js-sdk.js"></script> <script>alert("inside pg");</script>
<script src="childbrowser.js"></script>
<script src="js/jquery.js"></script>
<script src="js/angular.min.js"></script>
<script>alert("here");</script>
<script src="js/controllers.js"></script>
<script src="js/klass.min.js"></script>
<script src="js/code.photoswipe.jquery-3.0.5.min.js"></script>
<script src="js/maskedInput.js" type="text/javascript"></script>
<script src="js/jquery.joyride.js"></script>
<script src="js/jquery.fancybox.pack.js"></script>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
Scripts:
alert("p2 adding")
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
alert("main.html: device is ready");
}
$(window).load(function(){
alert("window.load happening");
})
</script>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-42023187-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42023187-1', 'openvino.com');
ga('send', 'pageview');
</script>
<script type="text/javascript">
var objectToLike = window.location;
var FBactivated = false;
FB.init({
appId : '659381964079214', // App ID
channelURL : '', // Channel File, not required so leave empty
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true,
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
getFriends();
testAPI();
FBactivated = true;
}
});
function getFriends() {
var fbUserIDs = []
FB.api('/me/friends', function(response) {
if(response.data) {
$.each(response.data,function(index,friend) {
var id = friend.id;
fbUserIDs.push(id);
});
var dataString = "fbUserIDs="+fbUserIDs.join();
$.ajax({
type: "POST",
data: dataString,
async: false,
url: "http://m.openvino.com/Scripts/faveMatch.php"
}).done(function(data){
console.log(data);
window.localStorage.setItem("fbFriends", data);
console.log("Saved");
});
} else {
alert("Error!");
}
});
}
function testAPI() {
FB.api('/me', function(response) {
//console.log(response, response.email);
var dataString2 = "id=" + response.id;
dataString2 += "&first_name=" + response.first_name;
dataString2 += "&last_name=" + response.last_name;
dataString2 += "&email=" + response.email;
console.log(dataString2);
$.ajax({
type: "POST",
url: "http://m.openvino.com/Scripts/fbconnect.php",
data: dataString2
}).done(function(data){
var dataJSON = $.parseJSON(data);
if (dataJSON[0].STATUS == "FAILURE") {
//console.log(dataJSON[0].MESSAGE);
return false;
} else if (dataJSON[0].STATUS == "SUCCESS") {
window.localStorage.setItem('email',dataJSON[0].COOKIE.email);
window.localStorage.setItem('password',dataJSON[0].COOKIE.password);
window.localStorage.setItem('name_first',dataJSON[0].COOKIE.name_first);
window.localStorage.setItem('name_last',dataJSON[0].COOKIE.name_last);
window.localStorage.setItem('uID',dataJSON[0].COOKIE.uID);
window.localStorage.setItem('phone',dataJSON[0].COOKIE.phone);
window.localStorage.setItem('firstTime',dataJSON[0].COOKIE.firstTime);
}
});
});
}
function fbLogout() {
if (FBactivated) {
try {
FB.logout(function(response) {
window.location.href = "index.html";
});
} catch (err) {
window.location.href = "index.html";
}
} else {
window.location.href = "index.html";
}
}
$(document).ready(function() {
alert("document.ready loaded");
$("#logmeout").click(function(e){
e.preventDefault();
window.localStorage.clear();
fbLogout();
return false;
});
$('.back_btn').click(function(e) {
$('.profile_menu').hide();
history.back();
});
$(document).click(function(e) {
$('.profile_menu').hide();
})
$('.profile_btn').click(function(e) {
$('.profile_menu').slideToggle();
e.stopPropagation();
e.preventDefault();
return false;
});
$('.profile_menu a').each(function() {
$(this).click(function(e) {
$('.profile_menu').hide();
});
});
});
HTML:
<body ng-app="OpenVino">
<div id="fb-root"></div>
<div class="header-wrap">
<header>
<div ng-show="(page != 'list')" class="back_btn"></div>
<img src="imgs/logo_only.png" alt="OpenVino" />
<div class="profile_btn"></div>
</header>
</div>
<div class="profile_menu">
My Favorites
Contact OpenVino
Images
Logout
</div>
<div class="content {{page}}" ng-view></div>
I fixed it with a simple, but disheartening solution: You have to turn your multipage app into a one page app. Unfortunate how phonegap advertises that you can take your HTML, CSS, and JS and build it natively. All of the .js loaded on the second page wouldnt work until I changed my login to a partial and fooled around with the routing.

Resources