【发布时间】:2016-10-07 21:49:32
【问题描述】:
我一直在尝试找出一个简单的指令模式来控制 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>
指令:
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 的方法?任何建议表示赞赏。
【问题讨论】:
-
'currentTime' 的分辨率是多少?我知道
ontimeupdate大约每帧视频运行一次(每秒多次)-currentTime是否获得亚秒级精度?如果是这样,在$watch中,您可以在进行更改之前检查newVar和elem[0].currentTime之间的最小差异。
标签: angularjs html5-video