最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS ng-click and callback function - Stack Overflow

programmeradmin4浏览0评论

On my web application, there are two kinds of users: guests & logged. The main page loads the same content for each.

My goal :

  • When a registered user clicks the link, 2 ajax requests ($http) retrieve the data of another page and load them in a model.
  • If the user is a guest, another model appears saying that he has to register.

My link :

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

GuestAction :

$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 way, if a guest is spotted, we return false and stop the execution. If it's a regular user, we execute the function showOne. As I want to do 2 asynchronous requests one after the other, I chose to use the callback trick.

The problem is that showOne() is executed directly when ng-click is launched. I tried to pass showOne() as a string, and eval() the string in GuestAction, but the parameters bee undefined...

Any idea how to solve this problem? I want to use a generic method which fires a function only if the user is logged.

On my web application, there are two kinds of users: guests & logged. The main page loads the same content for each.

My goal :

  • When a registered user clicks the link, 2 ajax requests ($http) retrieve the data of another page and load them in a model.
  • If the user is a guest, another model appears saying that he has to register.

My link :

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

GuestAction :

$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 way, if a guest is spotted, we return false and stop the execution. If it's a regular user, we execute the function showOne. As I want to do 2 asynchronous requests one after the other, I chose to use the callback trick.

The problem is that showOne() is executed directly when ng-click is launched. I tried to pass showOne() as a string, and eval() the string in GuestAction, but the parameters bee undefined...

Any idea how to solve this problem? I want to use a generic method which fires a function only if the user is logged.

Share Improve this question edited Feb 27, 2014 at 14:48 Nanne 64.4k16 gold badges122 silver badges166 bronze badges asked Feb 27, 2014 at 14:26 MagisterMagister 331 silver badge4 bronze badges 1
  • showOne is executing because you are invoking it in the html. You need to pass it as showOne (without () ). Also don't use 'eval' in angularjs. – Wawy Commented Feb 27, 2014 at 14:53
Add a ment  | 

2 Answers 2

Reset to default 6

I would remend using a service and promises, see this AngularJS $q

You don't have to use a service for $http requests but that is just my preference, it makes your controller a lot cleaner

Here is the service with the promise:

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

    var service = {};

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

    return service;
});

And then in our controller we would call it something like so:

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

    $scope.guestAction = function($event, card) {
        myService.guestAction().then(function (data) {
            if (data) {
                alert('guest spotted !');
            } else {
                alert('user');
                // Then run your showOne
                // If this is also async I would use another promise
                $scope.showOne($event, card.id);
            }
        }, function (error) {
            console.error('ERROR: ' + error);
        })
    };
});

Now obviously you may have to change things here and there to get it working for your needs but what promises do is allow you to execute code and once the promise is returned then continue, I believe something like this is what you are looking for.

You have to pass functions as parameters without the parenthesis and pass in the parameters separately:

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

and

$scope.guestAction = function($event,id, 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');
            callbackB($event,id);
        }

    });

}
发布评论

评论列表(0)

  1. 暂无评论