Mar*_* Ni 5 html5-video angularjs
我一直试图找出一个简单的指令模式来控制html5视频/ youtube视频.
我想用"Angular方式"来做,因此将视频的属性绑定到对象模型.但是,当处理视频的"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>
Run Code Online (Sandbox Code Playgroud)
指示:
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);
}
}
})
Run Code Online (Sandbox Code Playgroud)
JSFiddler:http://jsfiddle.net/vQ5wQ/
::
虽然这似乎有效,但请注意,每次onTimeUpdate发射,它都会触发$watch.
例如,当视频运行到10秒时,它通知onTimeUpdate将模型更改为10,$ watch将捕获此更改并要求视频再次寻找10秒.
这有时会创建一个循环,导致视频有时滞后.
你认为有更好的方法吗?一种不会触发不必要的$ watch的方法?任何建议表示赞赏.
一些timeupdate 文档的摘录说,当您调用绑定到 timeupdate 的函数时
- 播放视频
- 移动播放控件上的位置指示器
因此,当播放被修改时,该事件就会被触发,并且您不需要显式 $watch 附加到该播放控件的模型。
这意味着您可以在 timeupdate 侦听器中进行更新,而不是在监视语句中进行外部模型到视频分配...但请确保检查像 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;
});
};
Run Code Online (Sandbox Code Playgroud)
另请注意:我不确定这与您相关,但是一旦视频结束,play()即使您将其设置为currentTime. 为了解决这个问题,您可以使用 $watch 语句来videoCurrenTime重新启动视频(如果视频已结束)。
您的原始代码不是很滞后,但这里有一个更新的小提琴,似乎有几秒钟的滞后(至少从我有限的测试来看): http://jsfiddle.net/B7hT5/