如何将值传递给 AngularJS $http 成功回调 [英] How to pass a value to an AngularJS $http success callback

查看:26
本文介绍了如何将值传递给 AngularJS $http 成功回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 AngularJS 应用程序中,我正在执行以下操作

In my AngularJS application I am doing the following

$http.get('/plugin/' + key + '/js').success(function (data) {
    if (data.length > 0) {
        console.log(data);
        // Here I would also need the value of 'key'
    }
});

现在我需要访问成功回调中的 key 值,即我需要知道在发出 get() 请求时它具有哪个值.

Now I need to access the key value within the success callback, i.e. I need to know which value it had when the get() request has been made.

任何最佳实践"如何做到这一点?

Any "best practice" how to do so?

PS:我可以执行以下操作,但有更好的方法吗?

PS: I can do the following, but is there a better way?

var key = config.url.split('/')[2];

推荐答案

解决方案 1:

$scope.key = key;
$http.get('/plugin/' + key + '/js').success(function (data) {
    if (data.length > 0) {
        console.log(data, $scope.key);
    }
});

解决方案 2(根据 Jim Hong 在他的回答中的观察更新):

Solution 2 (Updated per Jim Hong's observation in his answer):

$http.get('/plugin/' + key + '/js').success((function(key) {
    return function(data) {
        console.log(key, data);
    }
})(key));

这篇关于如何将值传递给 AngularJS $http 成功回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆