Question about $timeout

Continuing the discussion from Complex Items with Option Buttons:

I’m just curious as to why you would wrap the directive’s code in a $timeout function. You also didn’t apply its second argument (amount of time). Just looking into your tricks… :slight_smile:

 .directive('backImg', function($timeout){
  return function(scope, element, attrs){
    $timeout(function () {
      var url = attrs.backImg;
      var content = element.find('a');
        'background-image': 'url(',
        'background-size' : 'cover'



I’m using a timeout here so we can catch the next angular digest cycle. It doesn’t need a time argument, because I want it to happen right away in the next cycle.

Ok thanks that clear it up a bit, but leads me to ask why the $timeout is necessary, because I have written a similar directive that works without using it. I’m sure yours is better, but I’d like to know why.

.directive('bg', function () {
	return {
		link: function (scope, element, attrs) {
			if ( {
				element.css("background-image", "url(" + + ")");

It more or less just in case. If the directive has a compile function, you want to make sure you call this function next time is starts its digest