Using AngularJS in conjunction with the Facebook Software Development Kit

I am facing a challenge with angularjs.

I am trying to retrieve values within the Facebook SDK functions but I am unable to store them in variables.

The perfil_nombre and perfil_foto variables are returning as "undefined" and I need to assign them to the scope.

Is there any solution? I am completely lost.

login.controller('inicio_ctrl', function($scope, $http, $timeout, $window)
{
      var laspaginas;
      var response;
      var perfil_foto;
      var perfil_nombre;
      var resp;
      $scope.FBLogin = function()
      {
        FB.login(function(response) 
        {
            if(response.authResponse) 
            {
                FB.api('/me', function(response) 
                {
                    perfil_nombre = response.name; //<<<<<-------- good
                    FB.api('/me/picture?redirect=false', function(resp) 
                    {
                       perfil_foto = resp.data.url; //<<<<<-------- good
                    });
                });
            } 
            else 
            {
             console.log('User cancelled login or did not fully authorize.');
            }
        }, 
        { scope: 'email, public_profile, manage_pages,publish_pages,read_insights,user_friends, publish_actions'});
        $scope.perfil_foto = perfil_foto; //<<<<<-------- undefined
        $scope.perfil_nombre =  perfil_nombre; //<<<<<-------- undefined
});

Answer №1

Angular is known for its MVC or MV* architecture. To prevent conflicts with other frameworks, it's recommended to separate your logic by creating a service and injecting it into the controller. This approach helps in avoiding any negative interactions between Angular and external libraries as it can be tricky to predict how they will interact.

A simple way to achieve this is by first making sure your function works using plain JavaScript, and then encapsulating it within a .factory or .service.

For instance:

(function(){
    'use strict';
    login.factory('FBService', FBService);

    FBService.$inject = [(/*List any necessary dependencies*/)];
    function FBService(/*List any necessary dependencies*/){
        var profileObject;
        
        //Add your JavaScript logic here

        function getPhoto(){
            return profileObject.photo;
        }

        return {getPhoto: getPhoto}
    }
})();

(function(){
    'use strict';
    login.controller('inicio_ctrl', inicioCtrl);

    inicioCtrl.$inject = ["$scope", "$http", "$timeout", "$window", "FBService"];
    function inicioCtrl($scope, $http, $timeout, $window, FBService){
        var ctrl = this;

        ctrl.login = function(){
            ctrl.profile_photo = FBService.getPhoto();
        }
    }
})();

If you can ensure that the JavaScript code functions independently of Angular, it will make integrating it seamlessly into Angular much easier.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Save data using firebase with a customizable and dynamic key title

I am currently working on adding the user's selected month to my database. saveInBdd (){ this.errors = []; const user = firebase.auth().currentUser; user.updateProfile({ displayName: this.firstname, }).then(()=>{ this.saveUserToUs ...

Using AngularJS to chain promises

After coming across some advice on AngularJS validation and promises, I am interested in creating a chain of confirmation dialogs to validate multiple steps at once. By making an API call based on user input, we can determine what steps require confirmati ...

express body parser is altering the date field within the body of a POST request

When a date field is sent in a POST request in the local time zone from the client side and received by the body parser, the date gets changed. The left side shows the client payload and the right side shows what is parsed on the server side: https://exa ...

Tips on efficiently adding and removing elements in an array at specific positions, all the while adjusting the positions accordingly

My challenge involves an array of objects each containing a position property, as well as other properties. It looks something like this: [{position: 1, ...otherProperties}, ...otherObjects] On the frontend, these objects are displayed and sorted based on ...

Challenges with UV wrapping in THREE.js ShaderMaterial when using SphereBufferGeometry

Currently, I am attempting to envelop a SphereBufferGeometry with a ShaderMaterial that incorporates noise to mimic the surface of Jupiter. However, the wrapping on the sphere geometry is turning out peculiarly. Instead of wrapping around the 'planet& ...

Encountering a 404 error when attempting to make an Axios post request

Utilizing Axios for fetching data from my backend endpoint has been resulting in a 404 error. Oddly enough, when I manually enter the URI provided in the error message into the browser, it connects successfully and returns an empty object as expected. Her ...

What is the preferred method for storing JSON data - using a single data attribute or multiple separate data attributes?

When it comes to storing multiple data attributes for a single DOM element, the question arises: Is it better to have a single data attribute containing JSON data, or is it more efficient to have separate data attributes for each value needed? <select ...

Retrieving hashtags from a text

If I had a string like this var feedback = "Yum! #yummy #delicious at #CZ" Is there an efficient way to extract all the hashtags from the string variable? I attempted using JavaScript's split() method, but it seems cumbersome as I have to repeate ...

Unlocking the JSON data for a specific id through an onClick event

Using axios to fetch data from an API and display it is working perfectly fine for me. Now, I am trying to extract each value and show the returned data when I click on a "TableRow" element. This is the JSON data I am dealing with: https://i.sstatic.net/T ...

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

Javascript code for toggling the visibility of a div element not functioning as expected

This problem is becoming quite frustrating as it appears to be straightforward but still doesn't work. Inside my document, I have <div id ="splashscreen" style="display:block"> <h3>title</h3> <p>text</p> &l ...

Tips for safeguarding your passwords across diverse authentication methods

Exploring a new project idea, I am interested in supporting the SASL Mechanisms for authentication, particularly PLAIN and DIGEST-MD5. I am curious about how to securely store users' passwords when implementing these two authentication methods. When ...

Style the div element with CSS

Is there a way to style a div element within an HTML document using Sencha framework? I have specific CSS properties that I would like to apply to my div. #logo{ position:absolute; top:20%; left:0%; } Below is a snippet of my Sencha code: Ex ...

What could be the reason why I am unable to load the ejs file?

https://i.stack.imgur.com/91bPg.png Issue: Unable to find the "index.ejs" view in the views directory ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

What could be causing my bootstrap-switch to malfunction?

Here is the snippet of code I am working with: jQuery.each($('.onoffswitch-checkbox'), function(i, slotData) { console.log($(slotData).bootstrapSwitch('state')) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1 ...

Unable to successfully import data from vue using vue-chartjs

Encountering an error in my Vue 2 project after compilation: Failed to compile. ./node_modules/vue-chartjs/dist/index.js 85:11-26 "export 'defineComponent' was not found in 'vue' The specific line in the above file triggering thi ...

The v-model for two-way binding seems to be malfunctioning, with a browser error or warning stating that the use of withDirectives is restricted to render functions

Currently utilizing VITE v5.0.8. This file is dex.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content=&q ...

The completion action is never carried out

I am currently facing an issue with one of my JavaScript functions. I have several $.ajax calls throughout my webpage followed by .done(), and they all seem to be functioning properly, except for one. Can anyone identify what could be causing the error? m ...

How do I attach an event listener to a select box that is created dynamically using JavaScript?

I'm new to web development and I'm currently working on a project where I need to create a select box dynamically within a div that is also created dynamically when the page loads. However, I'm facing an issue with adding an onchange Event L ...