0

I am relatively new to Angular.

I have a html document in which angular creates a html table with ng-repeat. When this table has been built, I would like to apply to it a Jquery function. How can I do that ?

function : $("#creneaux").footable()

If I apply the function in the controller when it is instantiated, nothing happens. when I apply it in the javascript console when the page has been displayed, it works.

Serge Tahé
  • 1,869
  • 2
  • 19
  • 20
  • Have a look at directives. That's where your jQuery must be usually: https://docs.angularjs.org/#!/guide/directive – Riron May 14 '14 at 12:19

2 Answers2

0

Firstly, I would move the $("#creneaux").footable() into a directive.

Solution:

Use $timeout without a delay to (a bit simplified) put the action at the end of the browser event queue after the rending engine:

app.directive('tableCreator', function($timeout) {
  return {
    link: function(scope, element, attrs) {

      $timeout(function() {
        $("#creneaux").footable();
      });
    }
  };
});

Demo: http://plnkr.co/edit/b05YKhipeVmrVHu2Xzsm?p=preview

Good to know:

Depending on what you need to perform, you can instead use $evalAsync:

app.directive('tableCreator', function($timeout) {
  return {
    link: function(scope, element, attrs) {

      scope.$evalAsync(function() {
        $("#creneaux").footable();
      });
    }
  };
});

The difference is that now the code will run after the DOM has been manipulated by Angular, but before the browser re-renders.

This can in certain cases remove some flickering that might be apparent between the rendering and the call to for example the jQuery plugin when using $timeout.

In the case of FooTable, the plugin will run correctly, but the responsiveness will not kick in until the next repaint, since the correct dimensions are not available until after rendering.

tasseKATT
  • 38,470
  • 8
  • 84
  • 65
  • Your solutions worked and also the one of Prashanth (without the timeout). Is there any difference ? – Serge Tahé May 14 '14 at 14:42
  • Try the demo I linked without the $timeout, and you will notice that the responsiveness won't work correctly until you resize the window. – tasseKATT May 14 '14 at 16:21
0

Try writing a directive.

app.directive('sample', function() {
    return {
        restrict: 'EA',     
        link: function(scope, element, attrs) {
            // your jquery code goes here.
        },
    };
});

Learn to write everything in angular instead jquery. This may help you "Thinking in AngularJS" if I have a jQuery background?

Community
  • 1
  • 1
JSAddict
  • 12,407
  • 7
  • 29
  • 49