我正在尝试将 video.js
库连接到我的应用程序中。在应用程序的一部分,用户能够上传可能包含视频的文件,因此在输出时,我使用 ng-repeat
循环播放视频上传,并输出 HTML5
视频标签。我现在想将指令附加到视频标记,以便 video.js
可以与其一起使用。
我的视频输出定义为
<video ng-src="{{video.url}}" ng-repeat="video in post.attachments.video" type="{{video.mimetype}}" controls preload="metadata" id="video_{{video.id}}" video>
对于我的 video
指令,我本质上只是想运行 videojs
函数来设置它,所以我想调用
videojs(attrs.id, {
controls: true,
preload: "metadata",
techOrder: ["flash"]
}, function() {});
正在调用此指令,但我遇到的问题是,当调用此指令时,ng-repeat
尚未完成所有操作,因此 attrs.id
仍然是 video_{{video.id}}
而不是我想要的类似 video_23
的内容。
我如何才能等到 ng-repeat
完成其工作后再运行我的视频指令,以便我知道我可以使用 ID 属性?
我目前使用的是 Angular 1.1.4。
现在,我的指令已经
app.directive("video", function($parse) {
"use strict";
return {
restrict: "A",
link: function(scope, elm, attrs) {
videojs(attrs.id, {
controls: true,
preload: "metadata",
techOrder: ["flash"]
}, function() {});
}
};
});
最佳答案
问题是当您尝试访问内插值时尚未执行字符串内插。您可以使用 attrs.$observe(...)
来完成此任务。这是link阅读 AngularJS 文档(或阅读下面的内容)。
...
link: function(scope, element, attrs) {
attrs.$observe('id', function() {
videojs(attrs.id, {
controls: true,
preload: "metadata",
techOrder: ["flash"]
}, function() {});
});
}
...
我还创建了一个plunker显示出这种行为。
编辑:更新了正确答案。
编辑 2:来自 Angular 文档:
Use
$observe
to observe the value changes of attributes that contain interpolation (e.g.src="{{bar}}"
). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.
关于html - 与 ng-repeat 相同元素上的指令,需要 ng-repeat 首先运行并使用其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17385358/