Search code examples
angularjsjquery-uiangularjs-directiveresizeangular-ng-if

Using ng-if in a custom directive template causing trouble to bind resizing event to element


Im putting my Pop-UP ( i.e bootstrap pop up) directive multiple time on a page. The pop up appear only if ng-if is true, sent as attribute parameter,but the jQuery resizing function is not binded to the element in link function of the directive.

This my first line of HTML in my directive

<div  class='ng-modal' id='Modal1' ng-if='show'>

The show is true when I click a button,the pop appear in UI but

$('#ModalDialog').resizable()

is not fired upon. Although if I do something like this

$timeout(function () {$('#Modal1').resizable() }, 1000);

then it work fine but $timeout function is not allowed in my code. what would be the proper technique to do this?

My finding: the problem only arise when the directive is putted multi-time on a a page, single call with ng-show causing no trouble.


Solution

  • Since JQuery relies on existing DOM elements, during the execution of

    $('#ModalDialog').resizable()
    

    An element with "#ModalDialog" might or might not exist. I am not familiar with JQuery resizable but when you need to apply JQuery on elements in angular the best practice is creating a directive and working with the DOM in the link function. This will ensure non-angular behaviour is properly applied to an element.

    .directive('uiResizable', function() {
    return {
        restrict: 'A',
        scope: ...,
        templateUrl: ...,
        link: function(scope, element, attrs) {
            element.resizable();
        }
      };
    });
    

    And to apply JQuery resizable to an element:

    <div id="#ModalDialog" ui-resizable ng-if ...>
    

    I hope this helps you.