【问题标题】:AngularJS $apply not working after ngChange on input type range在输入类型范围的ngChange之后AngularJS $apply不起作用
【发布时间】:2014-10-02 18:58:32
【问题描述】:

我不确定我正在做的事情是否允许或可能,但基本上我有一个使用 html5 音频元素的简单音频播放器。

app.factory('audio', function($document) {
    var audio = $document[0].createElement('audio');
    return audio;
});

然后在我看来,我有一个搜索范围输入

<input id="seek" type="range" min="0" ng-model="seek" ng-change="seeked()" max="{{max}}" value="{{seek}}">

在我的控制器上,我有以下内容:

app.controller('PlayerController', function($rootScope, $scope, audio) {

    //triggered by ngChange to update audio.currentTime
    $scope.seeked = function(){
        audio.currentTime = this.seek;
    };

    $scope.updateUI = function(seek, max){        
        $scope.max = max;
        $scope.seek = seek;
    };

    audio.addEventListener('timeupdate', function(){
        seek = audio.currentTime;
        max = audio.duration;          
        $rootScope.$apply($scope.updateUI(seek, max));           
    });
}

我的问题是,当我点击播放时,范围输入元素正在更新,这正是我想要的。但是当我更改输入值(移动滑块/搜索)时,歌曲会准确跳转到我放置滑块的位置,但之后滑块不再更新。

为此我采取的另一种方法是使用 jqLit​​e 并使用以下内容更新 'timeupdate' 事件中的输入范围值:

angular.element('#seek').val(audio.currentTime);

这很好用,但我想尽可能避免使用 jqLit​​e,除非没有其他解决方法。有人可以启发我吗?顺便说一句,我正在使用 Ionic 框架,对此我很陌生。

【问题讨论】:

  • 你有没有试过在改变currentTime后调用seeked函数中的$apply?
  • @JaredReeves,你的意思是在 seeked() 中再次调用 $apply?
  • 是的,有可能在寻求该值更改之前运行另一个应用程序。我不确定这是否可行,这只是一个建议。
  • 它没有。日志说:错误:[$rootScope:inprog] $apply 已经在进行中
  • 调用 $rootScope.$apply() 也是一个更好的解决方案,将其包装在 $timeout 中(“timeupdate”中的代码),没有设置间隔。这样做会强制执行摘要在 $timout 调用之后循环

标签: javascript angularjs ionic-framework


【解决方案1】:

终于找到问题了。

答案来源可以在here找到。

根据他(Calendee)的说法,点符号和原型继承应该始终遵守。

所以我更新了我对ff的看法:

<input type="range" min="0" ng-model="data.seek" ng-change="seeked();" max="{{max}}" value="{{data.seek}}">

然后在我的控制器上:

app.controller('PlayerController', function($timeout, $scope, audio) {

    //init vars
    $scope.data = {};

    //triggered by ngChange to update audio.currentTime
    $scope.seeked = function(){
        audio.currentTime = this.data.seek;
    };

    $scope.updateUI = function(seek, max){        
        $scope.max = max;
        $scope.data.seek = seek;
    };

    audio.addEventListener('timeupdate', function(){
        seek = audio.currentTime;
        max = audio.duration;

        //did a little change here by using $timeout         
        $timeout(function(){
            $scope.updateUI(seek, max)
        }, 0);           
    });
}

可以在here找到其他参考资料。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    相关资源
    最近更新 更多