JavaScript 变量使用外部函数
javascript variable use outside function
$scope.pagination_data = function(page_data){
count = page_data.data.count;
};
console.log("outside count is",count);// this not working
var page = function(){
userService.paginate()
.then(function(user){
$scope.pagination_data(user);
console.log("count is",count);//this is works
});
};
在该代码中,我正在使用$http服务,我正在获取数据AFTR,我想要一个计数,然后我也得到计数,但现在我希望在控制器中访问这个计数变量,但这对我来说无法访问。 我该怎么办..?
实际上,两者都有效,但您在错误的时间调用了第一个。
.then()
表示paginate()
返回一个承诺。这应该暗示它是异步的。
为了证明这一点,请使用setTimeout
延迟调用您的第一个控制台.log
$scope.pagination_data = function(page_data){
count = page_data.data.count;
};
setTimeout(function(){
console.log("outside count is",count);// this should work
}, 5000); // wait 5 seconds before calling the code above
// If 5 seconds is not long enough increase it to 10 or something
var page = function(){
userService.paginate()
.then(function(user){
$scope.pagination_data(user);
console.log("count is",count);//this is works
});
};
什么是异步代码?异步只是意味着稍后将调用代码。paginate().then()
所做的不是立即调用function(user)
函数,而是记住它应该在以后调用function(user)
(然后调用您的pagination_data
函数来设置count
的值(。然后它继续运行其他东西。
当没有其他代码要运行时,将处理事件循环,并且userService.paginate()
需要异步执行的任何操作都将得到处理。
当userService.paginate()
等待的任何内容最终返回(这可能是网络请求、用户单击等(时,最终调用function(user)
函数。这反过来又调用$scope.pagination_data()
这是将结果分配给全局count
变量的原因。
这setTimeout()
做什么?好吧,它的作用与我上面描述的相同。它不会立即呼叫console.log()
,而是记得稍后呼叫它。然后,当 5 秒(5000 毫秒(到期,并且没有其他 JavaScript 代码正在运行(这很重要,因为这意味着 javascript 可以运行事件循环(时,最终调用console.log()
。
只需在外面定义变量即可。
var count = 0;
$scope.pagination_data = function(page_data){
count = page_data.data.count;
};
console.log("outside count is",count);// this not working
var page = function(){
userService.paginate()
.then(function(user){
$scope.pagination_data(user);
console.log("count is",count);//this is works
});
};
fist 语句只定义函数,不调用它。如果有数据要传递给该函数,请在记录计数之前调用它。
// this only defines the function, doesn't call it
$scope.pagination_data = function(page_data){
count = page_data.data.count;
};
console.log("outside count is",count);// count is still unset
var page = function(){
userService.paginate()
.then(function(user){
$scope.pagination_data(user); // this is the call, count will be set
console.log("count is",count);//this will work
});
};
- HTML表单提交时未执行外部函数
- 从外部函数渲染后更改ReactJS类的状态
- 使用promise通过外部函数从DOM中检索属性
- 从内部函数javascript内部分配外部函数的对象
- JavaScript 变量使用外部函数
- 将外部函数返回的id传递给内部函数
- 使用ajax调用触发一个外部函数
- 内部函数不会为外部函数在 jQuery 中动态创建的元素赋值
- $location.search() 与外部函数一起使用,重置整个$scope.如何避免它
- 如何从许多内部非阻塞函数调用之一中提前退出外部函数
- Javascript,闭包中的返回函数如何与外部函数连接
- 从外部函数(数组)了解返回函数(x)
- Jquery:如何获取变量的局部外部函数
- 未调用的外部函数-javascript
- 如何将闭包从外部函数中提取出来,以便在不同的上下文中重用所述闭包
- 内部匿名函数如何具有外部函数的作用域
- 从外部函数获取参数名称
- javascript/google maps:为什么我在哪里初始化我的地图(内部与外部函数)很重要
- 如何将 THIS 绑定到 PHP 中的外部函数
- 如何在 javascript 中内部调用外部函数