How to use Colorbox with Angular JS

All we need is an easy explanation of the problem, so here it is.

How can I use colorbox (fancybox or lightbox is welcome too) with Angular JS, should I write a directive for it is there any other methods for it.

Here is my HTML:

...
<h2 class="box-header">
    <i class="icon-hdd"></i>    
    <div class="btn-group pull-right">      
        <a class="btn btn-mini">
            <i class="icon-zoom-in"></i>
            Expand
        </a>
    </div>
</h2>   
<div id="open-with-colorbox">
...
</div>
...

User will click expand button and div that has open-with-colorbox id will open as colorbox.

PS: I am new to Angular JS that’s why I am looking for a solution how to use colorbox, I use twitter bootstrap at my application.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Write a directive, it’s the best option.

Directive example:

app.directive('colorbox', function() {
  return {   
    restrict: 'AC',    
    link: function (scope, element, attrs) {        
      $(element).colorbox(attrs.colorbox);     
    }
  };  
});

HTML:

<a colorbox="{transition:'fade'}" href="..." rel="nofollow noreferrer noopener">Image</a>

Method 2

I have tried bmleite directive in my code but it doesnt work. The cboxElement class added to the element but colorbox didnt open when clicked. Finally i found this directive which worked like a charm.

app.directive('colorbox', function($compile, $rootScope){
  return {
    link: function(scope, element, attrs){
      element.click('bind', function(){
        $.colorbox({
          href: attrs.colorbox,
          onComplete: function(){
            $rootScope.$apply(function(){
              var content = $('#cboxLoadedContent');
              $compile(content)($rootScope);      
            })
          }
        });
      });
    }
  };
});

Then in your html section use it with:

<img src="path_to_image" colorbox="path_to_large_image" />

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply