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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:44:20  来源:igfitidea点击:

Update $scope from inside callback in angularJS

javascriptangularjsscopeangularjs-scope

提问by fmtoffolo

I have this controller and I would like to update the $scope.progressfrom within the function callback. I tried using $rootScopeand $scope.apply()but I can't get it to work. Is there something I'm missing?

我有这个控制器,我想$scope.progress从函数回调中更新它。我尝试使用$rootScopeand$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 $applyfunction on above script, and progressupdate. Try $applyafter 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.

推荐第一种方法。