Skip to content

Instantly share code, notes, and snippets.

@kranthilakum
Last active January 4, 2016 16:19
Show Gist options
  • Select an option

  • Save kranthilakum/8646658 to your computer and use it in GitHub Desktop.

Select an option

Save kranthilakum/8646658 to your computer and use it in GitHub Desktop.
Simple example to illustrate Angular directive
// Set image as background of a div element using CSS
.fill-bg {
  background-img: url('MYURLHERE');
  background-size : 'cover';
  background-repeat : 'no-repeat';
  background-position : 'center center';
}

/* Automate the above process using jquery, so that
 * designers don't have to write separate CSS class for each image 
 * Add cover-background-image to some <div> to set their background
 */
$('div[cover-background-image]').each(function(i, el) {
  $(element).css({
    'background-image': 'url()',
    'background-size' : 'cover',
    'background-repeat' : 'no-repeat',
    'background-position' : 'center center'
  });
});

// Angular directive module
angular.
  module('myApp', []).
  directive('myBackgroundImage', function () {
    return function (scope, element, attrs) {
      element.css({
        'background-image': 'url(' + attrs.myBackgroundImage + ')',
        'background-size': 'cover',
        'background-repeat': 'no-repeat',
        'background-position': 'center center'
      });
    };
  });

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment