javascript 从 angularJS 的内部回调更新 $scope
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22770857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update $scope from inside callback in angularJS
提问by fmtoffolo
I have this controller and I would like to update the $scope.progress
from within the function callback. I tried using $rootScope
and $scope.apply()
but I can't get it to work.
Is there something I'm missing?
我有这个控制器,我想$scope.progress
从函数回调中更新它。我尝试使用$rootScope
and$scope.apply()
但我无法让它工作。有什么我想念的吗?
progressupdate is a variable returned by the event. the code is not exactly like this. I made it super simple here to show the structure.
progressupdate 是事件返回的变量。代码并不完全像这样。我在这里非常简单地展示了结构。
app.controller('player', function($scope) {
var show = function(url) {
function(err, showOK) {
if (err) {
console.log(err);
} else {
showOK.on('listening', function(){
$scope.progress = progressupdate;
});
}
});
}
show(url);
});
Am I running that function incorrectly inside the controller? Should I use something like this?
我是否在控制器内错误地运行了该功能?我应该使用这样的东西吗?
$scope.show = function(url)...etc
回答by Iqbal Fauzi
I don't see the $apply
function on above script, and progressupdate. Try $apply
after set, or set it inside $apply
:
我没有$apply
在上面的脚本和progressupdate 上看到函数。$apply
设置后尝试,或将其设置在里面$apply
:
showOk.on('listening', function(){
$scope.$apply(function(){
$scope.progress = progressupdate;
});
});
or
或者
showOk.on('listening', function(){
$scope.progress = progressupdate;
$scope.$apply();
});
The first method is recommended.
推荐第一种方法。