我正在處理一個自定義指令,用於在狀態(使用ui-router
正在更改)時預加載圖像,以便在導航到新狀態之前解析數據和內容。自定義指令,用於預加載背景圖像不工作AngularJS
我創建了一個筆在這裏:https://codepen.io/wons88/pen/NgbNvO顯示我與bgSrc
指令的基本實現:
app.directive('bgSrc', ['preloadService', function (preloadService) {
return function (scope, element, attrs) {
element.hide();
preloadService(attrs.bgSrc).then(function() {
console.log(element.css);
element.css({
"background-image": "url('" + attrs.bgSrc + "')"
});
element.fadeIn();
});
}
}]);
和preloadService
:
app.factory('preloadService', ['$q', '$rootScope', function ($q, $rootScope) {
return function (url) {
var deffered = $q.defer(),
image = new Image();
image.src = url;
if (image.complete) {
$rootScope.loading = false;
deffered.resolve();
} else {
$rootScope.loading = true;
image.addEventListener('load',
function() {
deffered.resolve();
$rootScope.loading = false;
});
image.addEventListener('error',
function() {
deffered.reject();
$rootScope.loading = true;
});
}
return deffered.promise;
};
}]);
和HTML:
<div bg-src="https://images5.alphacoders.com/446/thumb-1920-446028.jpg">Background img should show up...</div>
編輯: 問題是,即使加載圖像也不會顯示(如chrome開發工具中的網絡選項卡所示)。如果我靜態應用樣式(或類),圖像顯示沒有問題,只是加載速度較慢...因此試圖應用該指令。
我知道在bgSrc
指令中發生了錯誤,但我無法找到它。對此事的任何幫助,將不勝感激:)
有什麼實際問題? –
@MikeFeltman我意識到我沒有說這個,會編輯我的帖子。該圖像沒有顯示,但是可以在chrome開發工具的網絡項目中加載和獲取 – w0ns88
@sachilaranawaka no。我創建了我自己的指令,名爲bgSrc(html中的bg-src) – w0ns88