Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force jQuery to "listen" for, and activate plugins on, future AngularJS ng-repeat elements?

Decently experienced with jQuery, new to AngularJS.

I have a page with a list of colors (variable number) with attached jQuery colorpickers (marked by class ".colorpicker"). On the static, PHP-generated version of the page, that works great; but converting it over to ng-repeat, jQuery doesn't catch future occurances.

Is there an event that can be caught with $.on(), or is there some other sneaky best-practices way to accomplish this with AngularJS? I've searched around, but every answer I've found has been how to set up $.on('click') or similar.

<ul class="unstyled">
  <li ng-repeat="color in showcolors">
    <input type="color" class="input-mini colorpicker" ng-model="color.hex"> {{color.category}}
  </li>
</ul>
like image 711
CJ Thompson Avatar asked Oct 22 '22 11:10

CJ Thompson


1 Answers

Anytime you want to manipulate the DOM or use a jQuery feature/plugin; it's time for a directive. You could add a directive to your ng-repeat that binds the jQuery colorpicker to the input field as it's being added to the DOM. Something like:

<ul class="unstyled">
  <li ng-repeat="color in showcolors">
    <input data-jq-colorpicker type="color" class="input-mini colorpicker" ng-model="color.hex"> {{color.category}}
  </li>
</ul>

And then add the directive:

yourApp.directive('jqColorpicker', function(){
    var linkFn = function(scope,element,attrs){
        // element here = $(this)
        // bind your plugin or events (click, hover etc.) here
        element.colorpicker();
        element.bind('click', function(e){
          // do something
        });
    }

    return {
        restrict:'A',
        link: linkFn
    }
});

Note, this is untested but should solve your problem. If you set up a Plunker or JSFiddle, I'll take a look.

Also, be sure to check out the jQuery passthrough feature of Angular UI.

like image 100
GFoley83 Avatar answered Oct 27 '22 10:10

GFoley83