Injecting Facebook JS SDK into AngularJS Controllers

Here’s a code snippet that I’m using to play with Facebook Js Sdk withing an Angularjs SPA.

I’m using this code to load the fb sdk when the user clicks on a button and then I check the login status and some permissions just to get the images feed from user’s facebook profile.

Html file

<div class="triggerFbUpload" ng-click='triggerFacebook();'>
    Upload pictures from facebook
</div>

My Angularjs controller

(function() {
    'use strict';
     var fbController = function($scope, facebookSdkService) {
         $scope.triggerFacebook = function() {
             facebookSdkService.loadSDK(document, 'script', 'facebook-jssdk'); //Sdk is now loading
	     facebookSdkService.initFbApp(); //Init app and do stuff with login answer
	};
    };
    angular.module('mainApp').controller('fbController', ['$scope', 'facebookSdkService', fbController]);
})();

FacebookSDK Service

(function() {
	'use strict';
	angular.module('mainApp').service('facebookSdkService', function() {
		var facebookSdkService = {
			loadSDK: 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/all.js";
				fjs.parentNode.insertBefore(js, fjs);
			},
			initFbApp: function() {
				function renderFacebookPhotos() {
					FB.api('/me/photos', function(response) {
						if (!response || response.error) {
							// render error
						} else {
							// render photos
						}
					});
				}

				function listenForLogin() {
					FB.Event.subscribe('auth.authResponseChange', function(response) {
						if (response.status === 'connected') {
							console.log('Logged in');
						} else {
							FB.login();
						}
					});
				}

				function getPhotos(uid) {
					/* make the API call to get the photos */
					FB.api(
						"/me/photos/uploaded",
						function(response) {
							if (response && !response.error) {
								/* handle the result */
								console.log('Now display the pictures!');
							}
						}
					);
				}

				function startLogin() {
					FB.login(function(response) {
						if (response.status === 'connected') {
							console.log('the user is logged in and has authenticated memorylife app');
							var uid = response.authResponse.userID;
							var accessToken = response.authResponse.accessToken;
							getPhotos(uid);
						} else {
							console.log('App not allowed!');

						}
					}, {
						scope: 'email,user_photos'
					});
				}

				window.fbAsyncInit = function() {
					FB.init({
						appId: xxxxxxx,
						secret: 'xxxxxxxxxxbf',
						status: true, // Check login status
						cookie: true, // Enable cookies to allow the server to access the  session
						xfbml: true // Parse XFBML
					});
					FB.getLoginStatus(function(response) {
						if (response.status === 'connected') {
							console.log('the user is logged in and has authenticated memorylife app');
							var uid = response.authResponse.userID;
							var accessToken = response.authResponse.accessToken;
							getPhotos(uid);
						} else {
							startLogin();
						}
					});

				};
			}
		};
		return facebookSdkService;
	});
})();

Do you know a better method? Let me know in the comments or on my twitter. Cheers!

How to use AngularJs with requireJs, jQuery, webGL and three.js

This is just the main file on the app. Feel free to use it in your app ;) Cheers!

angularjs-threejs-webgl-requirejs

require.config({
	baseUrl: 'javascripts',
	paths: {
		'jQuery': 'libs/jquery-1.10.2.min',
		'angular': 'libs/angular.min',
		'angular-route': 'libs/angular-route.min',
		'angular-resource': 'libs/angular-resource.min',
		'angular-animate': 'libs/angular-animate.min',
		'jQueryBootstrap': 'libs/bootstrap.min',
		'jQueryUI': 'libs/jquery-ui-1.10.3.custom.min',
		'jQueryNiceScroll': 'vendors/jquery.nicescroll.min',

		//WebGl Dependencies
		'ThreeLibrary': 'webgl/three',
		'OrbitController': 'webgl/OrbitControlsFS2',
		'DetectorWebGL': 'webgl/Detector'
	},
	shim: {
		'angular': {
			'exports': 'angular'
		},
		'angular-route': {
			deps: ['angular']
		},
		'angular-resource': {
			deps: ['angular']
		},
		'angular-animate': {
			deps: ['angular']
		},
		'jQuery': {
			'exports': 'jQuery'
		},
		'jQueryUI':{
			deps: ['jQuery']
		},
		'OrbitController':{
			deps: ['ThreeLibrary']
		},
		'DetectorWebGL':{
			deps: ['ThreeLibrary', 'OrbitController']
		}

	}
});

require(['jQuery', 'angular', 'angular-route', 'angular-resource', 'routes/mainRoutes'], function($, angular, mainRoutes) {
	$(function() {
		// using jQuery because it will run this even if DOM load already happened
		angular.bootstrap(document, ['mainApp']);
	});
});

Get search engines keywords referring to site

<?phph
// http://stevenyork.com/tutorial/how_to_get_search_engine_referal_keywords_using_php

// simply obtains the referal URL and uses the PHP function parse_url() to break things down. 

function getReferalHost()
{
    $refer = parse_url($_SERVER['HTTP_REFERER']);
    $host = $refer['host'];

    if(strstr($host,'google'))
    {
        return 'Google';
    }
    elseif(strstr($host,'yahoo'))
    {
        return 'Yahoo';
    }
    elseif(strstr($host,'msn'))
    {
        return 'MSN';
    }
}

//This next function (getKeywords) parses the referal URL again (not best practice is it? Shame on me). Then I've got a specific preg_match for each of the different vendors (based on the URLs that each of them uses. Google will format their query as such: http://www.google.com/search?&rls=en&q=seopher+another+keyword so I know that what I'm after starts with '&q=' with the keywords separated by '+'. So the regex used matches that. Yahoo and MSN do exactly the same, just with slightly different syntax - hence the need for the 'if' statement.
function getKeywords()
{
    $refer = parse_url($_SERVER['HTTP_REFERER']);
    $host = $refer['host'];
    $refer = $refer['query'];

    if(strstr($host,'google'))
    {
        //do google stuff
        $match = preg_match('/&q=([a-zA-Z0-9+-]+)/',$refer, $output);
        $querystring = $output[0];
        $querystring = str_replace('&q=','',$querystring);
        $keywords = explode('+',$querystring);
        return $keywords;
    }
    elseif(strstr($host,'yahoo'))
    {
        //do yahoo stuff
        $match = preg_match('/p=([a-zA-Z0-9+-]+)/',$refer, $output);
        $querystring = $output[0];
        $querystring = str_replace('p=','',$querystring);
        $keywords = explode('+',$querystring);
        return $keywords;

    }
    elseif(strstr($host,'msn'))
    {
        //do msn stuff
        $match = preg_match('/q=([a-zA-Z0-9+-]+)/',$refer, $output);
        $querystring = $output[0];
        $querystring = str_replace('q=','',$querystring);
        $keywords = explode('+',$querystring);
        return $keywords;
    }
    else
    {
        //else, who cares
        return false;
    }
}

// This final function is what I'm using to write the recommendations; it takes the keywords used as a parameter and uses MySQL scoring to deliver results... So it takes the search terms and tries to find similar content on the website:
function getSearchHelperList($term, $limit, $currentPageID)
{
    $searchterm = $term;

    //a function I use to sanitise all inputs
    $searchterm = $this->cleanInput($searchterm);

    /*query that takes the searchterms and scores it against the articles
    it also checks that the title isn't the same as the page we're already on
    because we don't want it showing you a link to your current page*/
    $sql = "SELECT CatID, Title, Content, CleanTitle, UNIX_TIMESTAMP(TIME) AS FORMATED_TIME, MATCH (Title, Content) AGAINST ('$searchterm') AS score FROM Articles WHERE MATCH (Title, Content) AGAINST ('$searchterm') AND CleanTitle != '$currentPageID' AND Time < CURRENT_TIMESTAMP ORDER BY score DESC";

    $result = mysql_query($sql);

    $num = mysql_numrows($result);

    if($num < $limit)
    {
        $limit = $num;
    }

    //old school right?  for loops! 
    //build an unordered list of related content
    if($limit > 0)
    {
        echo '<ul>';
        for($i=0; $i<$limit; $i++)
        {
            echo '<li><a href="/articles/'.mysql_result($result,$i,'CleanTitle').'">';
            echo mysql_result($result,$i,'Title');
            echo '</a></li>';
        }
        echo '</ul>';

    }
    else
    {
       //display a message
    }
}