在加载之前不要显示图像

时间:2016-03-14 10:17:40

标签: javascript html angularjs

function ascendingLinkSize(a, b) {
  return a.value - b.value;
  // return 0;
}
1)`Uninstall-Package NLog` :  Don't forget to delete Obj Folders manually
2)`Install-Package NLog` : Be sure you install the NuGet on the project you are working on

我有一个标题和图像的块。此块中的数据可以更改,因此应加载另一张图像 如果您的互联网连接速度较慢,您可以看到标题已更改,图片不是,因为它尚未加载。

Demo :(按// Code goes here angular .module('imgapp', []) .controller('mainCtrl', mainCtrl); function mainCtrl() { var vm = this; vm.first = { title: 'Image 1', url: 'http://www.image-mapper.com/photos/original/missing.png' } vm.second = { title: 'Image 2', url: 'http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg' } vm.primary = vm.first; vm.changeObject = function() { vm.primary = vm.second; } }加载新图片并更改标题)

如何在加载新图像之前隐藏旧图像?

注意:我不使用jQuery

4 个答案:

答案 0 :(得分:2)

Working demo

我刚刚创建了一个指令,它将在图像加载时调用函数。

.directive('imageonload', function() {
    return {
        restrict: 'A',
        scope: {
          ngShow : '='
        },
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                alert('image is loaded');
                scope.$apply(function(){
                    scope.ngShow = true;  
                });

            });
            element.bind('error', function(){
                alert('image could not be loaded');
            });
        }
    };
});

并修改了html,

<img ng-show="vm.isImageVisible" ng-src="{{vm.primary.url}}" imageonload >

答案 1 :(得分:0)

我相信您正在寻找ng-cloak指令:https://docs.angularjs.org/api/ng/directive/ngCloak

所以你的例子看起来像这样:

<body ng-controller="mainCtrl as vm">
  <button ng-click="vm.changeObject();">Change object</button>
  <div ng-cloak>
    <h1>{{vm.primary.title}}</h1>
    <img ng-src="{{vm.primary.url}}">
  </div>
</body>

http://plnkr.co/edit/rf8hM9JvR7EnjS1eWOgp?p=preview

答案 2 :(得分:0)

这可能会对您有所帮助:

var image = imageDomReferenceHere;
var downloadingImage = new Image();
downloadingImage.onload = function(){
   image.src = this.src;   
};
downloadingImage.src = "image path here";

http://blog.teamtreehouse.com/learn-asynchronous-image-loading-javascript

答案 3 :(得分:0)

您可以通过两个步骤完成。首先添加 ng-show 以在加载时隐藏或显示元素。第二次使用 onLoad 事件来了解何时完成加载。我从这个answer

中选择了指令

<强> HTML

vm.notLoading = true;
vm.imageLoaded = imageLoaded;

<强>指令

function imageonload() {
    return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        element.bind('load', function() {
            //call the function that was passed
            scope.$apply(attrs.imageonload);
        });
    }
}

<强>控制器

...

vm.notLoading = true;
vm.imageLoaded = imageLoaded;

...

vm.changeObject = function() {
    vm.notLoading = false;
    vm.primary = vm.second;
}

function imageLoaded() {
    vm.notLoading = true;
}

plunker