gpt4 book ai didi

AngularJS:两种方式将视频的 currentTime 与指令绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 21:16:28 24 4
gpt4 key购买 nike

我一直在试图找出一个简单的指令模式来控制 html5 视频/youtube 视频。

我想以“Angular 方式”来做,从而将视频的属性绑定(bind)到对象模型。但是,在处理视频的“currentTime”属性时我遇到了一些问题,因为它会不断更新。

这是我到目前为止得到的:

html控件:

<!--range input that both show and control $scope.currentTime -->
<input type="range" min=0 max=60 ng-model="currentTime">

<!--bind main $scope.currentTime to someVideo directive's videoCurrentTime -->
<video some-video video-current-time="currentTime"> </video>

指示:
app.controller('MainCtrl', function ($scope) {
$scope.currentTime = 0;
})

app.directive('someVideo', function ($window) {
return{
scope: {
videoCurrentTime: "=videoCurrentTime"
},
controller: function ($scope, $element) {

$scope.onTimeUpdate = function () {
$scope.videoCurrentTime = $element[0].currentTime;
$scope.$apply();
}
},
link: function (scope, elm) {
scope.$watch('videoCurrentTime', function (newVar) {
elm[0].currentTime = newVar;

});
elm.bind('timeupdate', scope.onTimeUpdate);
}
}

})

JSFiddler: http://jsfiddle.net/vQ5wQ/

::

虽然这似乎可行,但请注意每次 onTimeUpdate触发,它会触发 $watch .

例如,当视频运行到 10 秒时,它通知 onTimeUpdate 将模型更改为 10,$watch 会捕捉到这个更改并要求视频搜索到 10 秒 再次 .

有时 创建一个循环 这会导致视频不时滞后。

你认为有更好的方法来做到这一点吗?一种不会触发不需要的 $watch 的方法?任何建议表示赞赏。

最佳答案

摘自一些 timeupdate documentation表示绑定(bind)到 timeupdate 的函数在您调用时被调用

  • Play the video
  • Move the position indicator on the playback controls


因此,当播放被修改时,事件会被触发,并且您不需要显式地 $watch 附加到该播放控件的模型。

这意味着您可以在 timeupdate 监听器中进行这两项更新,而不是在 watch 语句中分配外部模型到视频...但请确保您检查他的评论中提到的 jkjustjoshing 之类的阈值,以便成为确保控件实际上已被移动。
$scope.onTimeUpdate = function () {
var currTime = $element[0].currentTime;
if (currTime - $scope.videoCurrentTime > 0.5 ||
$scope.videoCurrentTime - currTime > 0.5) {
$element[0].currentTime = $scope.videoCurrentTime;
}
$scope.$apply(function () {
$scope.videoCurrentTime = $element[0].currentTime;
});
};

另一个注意事项:我不确定这与您是否相关,但是一旦视频结束,它不会再次播放,直到您明确调用 play()即使你设置它的 currentTime .要解决这个问题,您可以在 videoCurrenTime 上使用 $watch 语句。如果视频已经结束,它会重新启动视频。

您的原始代码不是很滞后,但这是一个更新的 fiddle ,似乎有几秒钟的滞后(至少来自我的有限测试):
http://jsfiddle.net/B7hT5/

关于AngularJS:两种方式将视频的 currentTime 与指令绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com