Search code examples
angularjseventsangularjs-directivedom-manipulation

How to add an element and bind an event to it?


I want to make a resize-directive. Therefore I want to create a new element (the resizer) and bind an event to it, but in my code the event is bind to the directive-rootElement:

elm.append('<div class="iwResizable__resizer"></div>').bind('mousedown', function ($event) {
                        startW = elm.prop('offsetWidth');
                        startH = elm.prop('offsetHeight');
                        initialMouseX = $event.clientX;
                        initialMouseY = $event.clientY;
                        $document.bind('mousemove', mousemove);
                        $document.bind('mouseup', mouseup);
                        $event.preventDefault();
                });

How can I bind the mousedown-event to my new div?

Here is a Plunker


Solution

  • If you are not using jQuery (which you don't seem to), you should do the instantiation/binding and the appending in different statements:

    var resizer = angular.element('<div class="myResizable__resizer"></div>')
                         .bind('mousedown', function ($event) {...});
    elm.append(resizer);
    

    If you were using jQuery, you could use the appendTo() function (which is not implemented in JQLite), you could do it like this:

    $('<div class="myResizable__resizer"></div>').appendTo(elm).bind(...);