我正在使用指令使用 AngularJs 构建滑块,但现在我遇到了问题。这是我家的密码.html
<div class="loading" ng-hide="$root.showSlider">
<div class="logo">
<img class="" ng-src="./img/logo.png">
</div>
</div>
<slider-directive images="images" ng-show="$root.showSlider" ng-if="images"/>
现在我向控制器展示代码片段:
.controller("HomeController",["$scope","$rootScope", function($scope, $rootScope) {
(function getData() {
//do async call that return data
$scope.images = data;
}, function(err) {
console.log(err);
});
})();
}
]);
现在我可以显示我的指令的代码:
.directive('sliderDirective', function($rootScope, $interval) {
return {
restrict: 'E',
templateUrl: 'html/.../slider.html',
replace: true,
scope: {
images: '='
},
link: function(scope, element, attrs) {
scope.currentIndex = 0;
scope.next = function() {
scope.currentIndex < scope.images.length - 1 ? scope.currentIndex++ : scope.currentIndex = 0;
};
scope.prev = function() {
scope.currentIndex > 0 ? scope.currentIndex-- : scope.currentIndex = scope.images.length - 1;
};
scope.$watch('currentIndex', function() {
scope.images.forEach(function(image) {
image.visible = false; // make every image invisible
});
scope.images[scope.currentIndex].visible = true; // make the current image visible
$rootScope.showSlider = true;
});
$interval(function() {
scope.next();
}, 10000);
}
};
});
现在我的问题是了解何时加载滑块中的背景图像,以便我可以删除加载并显示滑块而不会产生不良影响。有没有一种方法可以告诉我何时加载所有图像或第一个图像?谢谢
您可以简单地为第一个图像(或所有图像 - 这取决于您)附加"load"事件处理程序。看看这个问题:
AngularJS - 图像"加载"事件
SamBarnes 创建了一个简单而漂亮的指令,它使您可以轻松附加加载事件处理程序并将其与角度控制器中的函数连接。
编辑
我提供了一个带有图像加载指令的示例解决方案。
1. 图像加载指令
angular.module('your_module')
.directive('imageLoaded', ['$parse', ImageLoadedDirective]);
function ImageLoadedDirective($parse) {
return {
restrict: 'A',
scope: {
imageLoaded: '&'
},
link: function (scope, elem, attrs) {
elem.on('load', function (event) {
scope.$apply(function () {
if (angular.isFunction(scope.imageLoaded)) {
scope.imageLoaded();
}
});
});
}
};
}
2.滑块模板(一个简单的ng重复图像)
...
<div ng-repeat="image in images">
<img ng-src="{{ image.src }}" image-loaded="imageLoadHandler()" />
</div>
...
3. 滑块指令
...
link: function(scope, element, attrs) {
// Number of currently loaded images
scope.loadedImagesCount = 0;
// Function executed when image is loaded
scope.imageLoadHandler = function() {
// Increase counter
scope.loadedImagesCount++;
// Check if number of loaded images equals slider's images count
if(scope.loadedImagesCount == scope.images.length) {
// Do something, when all images are loaded
alert('all loaded');
}
}
...
解释
我将图像加载指令附加到 ng-repeat 中的 img 元素,并使用它来在加载每个图像时通知滑块的控制器。在滑块指令的作用域中,我添加了一个计数器和一个简单的处理程序,它递增计数器并检查是否已加载所有图像。