Using AngularJS to handle ng-click events and callback functions

Within my web application, there exist two distinct user types: guests and logged users. Regardless of the user type, both are presented with identical content on the main page.

The objective :

  • Upon a registered user clicking a link, 2 ajax requests ($http) will be made to fetch data from another page and display it in a model.
  • If the user is a guest, a separate model will prompt them to register.

The link I have created :

<h4 ng-click="guestAction($event, showOne($event,card.id));">click me</h4>

GuestAction function :

$scope.guestAction = function($event, callbackB) {

    $http.get('/guest/is-guest/').success(function(data) {
        console.log("isGuest retrieved : " + data);
        if (data == 1)
        {
            alert('guest spotted !');
            return false;
        }
        else
        {
            alert('user');
            console.log(callbackB);
            eval('$scope.'+callbackB);
        }

    });

}

This approach ensures that if a guest is detected, the execution is halted by returning false. Conversely, for a regular user, the function showOne is executed. To manage consecutively fired asynchronous requests, I opted for the callback method.

An issue arises when showOne() is triggered instantly upon ng-click activation. I attempted passing showOne() as a string and utilizing eval() within GuestAction; however, the parameters were found to be undefined...

Are there any suggestions for resolving this dilemma? I aim to implement a universal procedure that triggers a function exclusively if the user is logged in.

Answer №1

If you're looking for a cleaner way to handle $http requests in AngularJS, I recommend using services and promises. Check out AngularJS $q documentation for more information.

While using a service for $http requests is not mandatory, it can greatly improve the organization of your controller code.

Here's an example of a service that utilizes promises:

app.factory('myService', function ($http, $q) {

    var service = {};

    service.guestAction = function () {
        var deferred = $q.defer();
        $http.get('/guest/is-guest/').then(function(response) {
            console.log("isGuest retrieved : " + response.data);
            if (response.data === 1) {
                deferred.resolve(true);
            } else {
                deferred.resolve(false);
            }
        }).catch(function(error) {
            deferred.reject('Error checking server.');
        });
        return deferred.promise;
    };

    return service;
});

In your controller, you can call the service like this:

app.controller('myController', function ($scope, myService) {

    $scope.guestAction = function($event, card) {
        myService.guestAction().then(function (result) {
            if (result) {
                alert('Guest spotted!');
            } else {
                alert('User');
                // You can then proceed with showOne
                // If showOne is also asynchronous, consider using another promise
                $scope.showOne($event, card.id);
            }
        }).catch(function (error) {
            console.error('ERROR: ' + error);
        })
    };
});

You may need to make adjustments based on your specific requirements, but using promises allows you to execute code asynchronously and continue once the promise is fulfilled. This approach can help streamline your code structure.

Answer №2

Make sure to provide functions as arguments without using the parentheses and supply the parameters separately:

<h3 ng-click="handleEvent($event, card.id, displayOne);">click here</h3>

also,

$scope.handleEvent = function($event, id, callbackFunction) {

    $http.get('/user/is-logged/').success(function(response) {
        console.log("isLogged result : " + response);
        if (response == 1)
        {
            alert('User is logged in!');
            return false;
        }
        else
        {
            alert('Visitor');
            callbackFunction($event, id);
        }

    });

}

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

Is there a way to remove a function from a constructor in JavaScript?

Is it possible to remove a function from a constructor? If the constructor for a Person object contains a function named greet, how would one go about eliminating this function? function Person(name) { this.name = name; ...

Select the card if the input spinner value is greater than zero

Hello, I am currently working on a front-end tool for quoting purposes. The user will need to click on a card and select which product they would like to add to their basket. There is also an input section available for the user to specify the quantity usi ...

How can I identify when a CSS transition on a particular element has ended if there are several transitions occurring simultaneously?

In my coding, I have been utilizing the following method to identify when a CSS3 transition has finished: CACHE.previewControlWrap.css({ 'bottom':'-217px' }).one('webkitTransitionEnd transitionend m ...

Creating Sequelize models with associations

Currently, I am working on developing a survey application using Node.js 6, Express.js 4, and Sequelize 4.4.2. As the user progresses through the survey, multiple model objects are being constructed but not saved in the database until the survey is complet ...

Issue with Electron and Node.js: Application fails to launch due to inability to locate the app within the modules

I am currently testing out an electron application that is supposed to link to our website. I decided to follow one of the tutorials available. Unfortunately, upon launching the app, I encountered the following error: Error log : akshay@akshay-mint-deskt ...

Callback in React Setstate triggered, leading to a delay in rendering

Recently, I embarked on a journey to learn React just 2 days ago. Despite my enthusiasm, I have encountered some challenges with React's setState method. As far as my understanding goes, I should utilize the prevState parameter when I need to alter th ...

Troubleshooting issue with AngularJS: Anchor tag with dynamic ng-click not functioning post compilation

I am attempting to dynamically add an anchor tag in HTML by using the following JavaScript code: var tabList = $sce.trustAsHtml('<a ng-click="getActiveTag()">Test</a>'); var temp = $compile(tabList)($scope); $scope.tabList = temp[0] ...

What is the most graceful way to manage devise's 401 error response when using AJAX?

Utilizing devise, one can employ before_filter :authenticate_user! to limit access solely to authenticated users. In the event an unauthenticated user attempts to access a restricted page, devise will automatically redirect them to the sign in page. Henc ...

Manipulating the .innerHTML property allows for selectively replacing sections

In my JavaScript code, I am trying to display a video along with a countdown timer. Once the countdown finishes, it should switch the content of the div to show a question. Below is my current implementation: <script type="text/javascript"> ...

Issues arising from Ionic's functionalities when separated controllers are implemented, resulting in

I utilized the yeoman generator to create an Ionic app. After starting the app with grunt serve, I added a new controller called settings. Index.html: <script src="scripts/controllers/settings.js"></script> Settings js: 'use strict&apo ...

Triggering the open() function within an Ajax request

Upon experimenting with the method open(), I discovered that it requires a URL file as an argument. For instance, I have two functions named generateGeometricShapes() and colorShapes(). I am contemplating whether I should create separate files for each fu ...

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

Unable to convert UTF-8 buffer to the specified data format

Before flagging this question as a duplicate, I want to clarify that I have already tried various solutions found in different threads to convert a buffer into an array of buffers, but none of them meet my requirements. I am currently using Node's ch ...

Is there a way to adjust the font size in Javascript/Html without changing the color?

I have a code snippet that creates a button to increment a variable, and I want to change the font size of the displayed variable. This code is for a game akin to cookie clicker. <div class="game-object"> <script type="text/javascript>"; var c ...

Issue with React submit button for posting data is not functioning as intended

My dilemma lies within a Modal component containing a Form and Button. The goal is to trigger a POST request (managed in a separate file) upon the user clicking the button, which will run a simulation using the validated input values. Surprisingly, the onC ...

Discovering common elements in various arrays of objects

Details: record1 = [{"site": "The Blue Tiger", "zipcode": "E1 6QE"}, {"site": "Cafe Deluxe", "zipcode": "E6 5FD"}] record2 = [{"site": "Blue Tiger", "zi ...

Retrieve Chosen Text from Array

Utilizing a dropdown and a textbox, the chosen option in the dropdown modifies the text in the textbox. I am curious about how to extract the selected value into an array and then assign the corresponding text from that array? The current working code is ...

Leveraging the power of the Google API within the Dojo module

Is it possible to integrate Google Maps API within a Dojo Toolkit module in the following way? define(["dojo/dom"], function (dom) { var input = dom.byId("searchBox"); var autocomplete = new google.maps.places.Autocomplete(input, options); } ...

Use bracket notation to verify if a property is undefined

Having some difficulty determining if the property value of an object is undefined when accessed dynamically with bracket notation. Here's a snippet of my code: function toBritishDate(date: Date | string): string { console.log(date) return &qu ...

AngularJS directive is triggering $watch callback functions upon initialization

I have developed a directive in AngularJS called leafletDirective, which includes various functionalities for working with Leaflet maps. leafletDirective = angular.module("leaflet-directive", []) leafletDirective.directive "leaflet", ($http, $log) -& ...