[英]AngularJS: ng-src behavior on non-standard attributes?
我正在使用“ Video For Everybody ”生成器在我的應用程序中集成媒體播放器。 如果瀏覽器不支持HTML5 video
和audio
,播放器具有閃回后備功能,我必須使用視頻和占位符(圖像)源構建具有param
屬性的object
元素。
正如預期的那樣,我遇到了經常出現的問題,即沒有及時解決,我的瀏覽器會向my.media.com/{{video.src}}
發送請求,而不是my.media.com/somevideo.mp4
不幸的是,我遇到了同樣的問題poster, flashvars, placeholder
有幾個屬性( 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>
你現在可以使用ng-attr-poster
,或者更普遍的: ng-attr-whatever
。
在官方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]);
});
}
};
};
});
鑒於上述情況,實現自己的指令應該是微不足道的。
因此,最通用,可維護,可配置和可重用的解決方案是創建一個可以為您處理它的自定義指令。
看看這個- > PLNKR < -幾乎所有你需要的東西。 你只需要弱一點。
工作原理:傳遞配置對象的指令(如果需要更多對象,只需創建其他屬性)。 元素可以處於兩種狀態:准備好還是不准備好。 並且$scope.isReady
只是說明是否收集了所有成分。 如果是這樣, ngSwitch
加載videoPlayer模板,因為所有信息都沒有發送不需要的請求。
我在video
標簽上遇到了與poster
屬性類似的問題。 如果將ng-cloak
應用於具有類似src
屬性的元素,則在刪除隱身時,它們不會嘗試加載任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.