Javascript AngularJS从$http.get函数访问作用域
我试图将作用域中的变量从$http.get.then函数改为$http.get.then函数,但它写的是未定义的。成功加载target.html,我已尝试并读取响应Javascript AngularJS从$http.get函数访问作用域,javascript,angularjs,google-chrome-extension,scope,Javascript,Angularjs,Google Chrome Extension,Scope,我试图将作用域中的变量从$http.get.then函数改为$http.get.then函数,但它写的是未定义的。成功加载target.html,我已尝试并读取响应 $scope.loaded_view = "before"; $scope.getView = function(name) { $http.get(chrome.extension.getURL("/views/" + name + ".html")).then(function(response, stat, x
$scope.loaded_view = "before";
$scope.getView = function(name) {
$http.get(chrome.extension.getURL("/views/" + name + ".html")).then(function(response, stat, xhr) {
$scope.loaded_view = "after";
});
console.log($scope.loaded_view); //--> before
}
$scope.getView('target');
console.log($scope.loaded_view); //—> before
这是因为执行
get请求需要时间
Javascript
从top
执行到bottom
您可以将$http
视为一个超时
服务,它会在几分钟后给出响应。我创建了一个plunker
来演示这一点
通过移动控制台进行检查。在获取功能中记录,并在响应发出后记录
$scope.loaded_view = "before";
console.log('this is printed first(1)')
$scope.getView = function(name) {
$http.get(chrome.extension.getURL("/views/" + name + ".html")).then(function(response, stat, xhr) {
$scope.loaded_view = "after";
console.log($scope.loaded_view); //--> after
console.log('this is printed third(3)')
});
console.log('this is printed second(2)')
}
$scope.getView('target');
为了更加清晰,我添加了三个console.log()
,您可以观察它们的顺序
为了让您更清楚,我添加了控制台的顺序:
这是第一次打印(1)
这是第二次打印(2)
这是第三(3)页
注意:
即使它在console.log中的之前打印,您的html
也会
当值更改时,使用新值更新
范围值更改时,角度运行<代码>摘要循环代码>
这是因为执行get请求需要时间
Javascript
从top
执行到bottom
您可以将$http
视为一个超时
服务,它会在几分钟后给出响应。我创建了一个plunker
来演示这一点
通过移动控制台进行检查。在获取功能中记录,并在响应发出后记录
$scope.loaded_view = "before";
console.log('this is printed first(1)')
$scope.getView = function(name) {
$http.get(chrome.extension.getURL("/views/" + name + ".html")).then(function(response, stat, xhr) {
$scope.loaded_view = "after";
console.log($scope.loaded_view); //--> after
console.log('this is printed third(3)')
});
console.log('this is printed second(2)')
}
$scope.getView('target');
为了更加清晰,我添加了三个console.log()
,您可以观察它们的顺序
为了让您更清楚,我添加了控制台的顺序:
这是第一次打印(1)
这是第二次打印(2)
这是第三(3)页
注意:
即使它在console.log中的之前打印,您的html
也会
当值更改时,使用新值更新
范围值更改时,角度运行<代码>摘要循环代码>
getView函数的用途是什么?您能说得更准确些吗?由于get()
的异步性质,在回调之前(然后)会解释console.log()
)getView函数的用途是什么?你能说得更准确些吗?由于get()
的异步性质,console.log()
在回调之前被解释(然后
),所以如果我将get()设为“非异步”,它会在console.log之前更改$scope吗?即使它之前在console.log
中打印,当值随作用域值的变化而变化时,html
将用当前值更新。@user1938361不能使其非异步。这就是$http.get()的确切用法。您向服务器发送一个请求,在此期间,您的JS代码可以继续运行,而不会在等待响应时被阻止。我可以通过发送Xhtmlrequest或JQuery使其非异步。因此,如果没有angularjs帮助,但是非异步
的性能会滞后,因为我们必须等待响应
,然后才能执行其他操作。因此,如果我将get()设为“非异步”,它会在console.log之前更改$scope吗?即使它之前在console.log
中打印,当值随作用域值的变化而变化时,html
将用当前值更新。@user1938361不能使其非异步。这就是$http.get()的确切用法。您向服务器发送一个请求,在此期间,您的JS代码可以继续运行,而不会在等待响应时被阻止。我可以通过发送Xhtmlrequest或JQuery使其非异步。因此,如果没有angularjs帮助,但是非异步
的性能会滞后,因为我们必须等待响应
,然后再做其他事情。