Mazzy
Mazzy

Reputation: 14179

background image isn't showed with the creation of the directive

This is my directive

(function() {
  'use strict';

  angular
    .module('app')
    .directive('backgroundImage', Background);

    function Background () {
      return function (scope, element, attrs) {
        scope.$watch(attrs.backgroundImage, function(value) {
          element.css({
            'background-image': 'url(https://example.com/' + value + '.jpg)',
            'background-repeat': 'no-repeat',
            'background-position': 'center center',
            'background-attachment': 'fixed',
            '-webkit-background-size': 'cover',
            '-moz-background-size': 'cover',
            '-o-background-size': 'cover',
            'background-size': 'cover'
          });
        });
      };
    }
}());

which I call from the view with the following code

<div background-image="id"></div>

My issue is that despite the image has been loaded correctly it isn't showed into the view. Do you have any idea?

Upvotes: 0

Views: 43

Answers (1)

PSL
PSL

Reputation: 123739

You need to provide height as well, in order for the background image to be visible, also width if needed. Since there is no content inside that div it will be at 0 height. div being a block element will take the full width of its container if not specific width is mentioned.

Example:

      element.css({
        'background-image': 'url(https://example.com/' + value + '.jpg)',
        'background-repeat': 'no-repeat',
        'background-position': 'center center',
        'background-attachment': 'fixed',
        '-webkit-background-size': 'cover',
        '-moz-background-size': 'cover',
        '-o-background-size': 'cover',
        'background-size': 'cover',
        'height' :'200px'
      });

Set the height and width via css if you have a preset one. If you need to make it flexible calculate the height and width by creating an temp image object.

scope.$watch(attrs.backgroundImage, function(value) {
        var url = 'https://example.com/' + value + '.jpg';

        getImageDimensions(url).then(function(dimObj) {

          element.css({
            'background-image': 'url(' + url + ')',
            'background-repeat': 'no-repeat',
            'background-position': 'center center',
            height: dimObj.height,
            width: dimObj.width
          });
        })
      });

      function getImageDimensions(url) {
        var defer = $q.defer();
        var img = new Image();

        img.onload = function() {

          defer.resolve({height: img.height + 'px', width:img.width + 'px'});
          img = null;
        }

        img.onerror = function(){
          defer.reject("Ivalid url");
          img = null;
        }

        img.src = url;
        return defer.promise;
      }
    };
  }

Upvotes: 1

Related Questions