Ind*_*dex 15 angularjs angularjs-directive
我正在使用" Video For Everybody "生成器在我的应用程序中集成媒体播放器.如果浏览器不支持HTML5 video,则播放器具有闪回的后备功能,并且audio我必须使用视频和占位符(图像)源构建object具有param属性的元素.
正如预期的那样,我遇到了经常出现的问题,即表达式没有得到及时解决,我的浏览器发送请求my.media.com/{{video.src}}而不是my.media.com/somevideo.mp4
不幸的是,有几个属性(poster, flashvars, placeholder仅举几例)我面临同样的问题.我将如何创建与ng-src或ng-href指令相同的行为?我试着寻找相关的源代码,但我还没有找到它.这是一个片段,展示了有问题的HTML,
<video controls="controls" poster="{{mediaModel.mediaFile2}}" width="300" height="150">
<source ng-src="{{mediaModel.mediaFile}}" type="{{mediaModel.contentType}}" />
<object type="application/x-shockwave-flash" data="http://player.longtailvideo.com/player.swf" width="300" height="150">
<param name="movie" value="http://player.longtailvideo.com/player.swf" />
<param name="allowFullScreen" value="true" />
<param name="wmode" value="transparent" />
<param name="flashVars" value="{{'controllerbar=over&image=' + media.mediaFile2 + '&file=' + mediaModel.mediaFile}}" />
<img ng-src="{{mediaModel.mediaFile2}}" width="300" height="150" title="{{mediaModel.uploadedTime}}" />
</object>
Run Code Online (Sandbox Code Playgroud)
在官方API文档中可以轻松找到内置指令的来源.在这种情况下,请转到ngSrc的文档,在页面顶部您将看到两个按钮,"改进此文档"和"查看源代码",单击"查看源代码",它将自动将您带到正确的源文件指令定义的位置.这适用于所有内置指令,非常方便!
下面我粘贴了ngSrc的代码,有趣的是它看起来并不复杂,关键的一行似乎是priority: 99,根据它旁边的注释意味着优先级为99的指令将在内插属性后运行.
// ng-src, ng-srcset, ng-href are interpolated
forEach(['src', 'srcset', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
if (!value)
return;
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie) element.prop(attrName, attr[attrName]);
});
}
};
};
});
Run Code Online (Sandbox Code Playgroud)
鉴于上述情况,实现自己的指令应该是微不足道的.