angularjscornerstonejs

How can I convert custom jquery event listener into angularjs listener?


I have created angularjs component. I wrote a custom event listener in jquery, event is triggered by non-angularjs library.

$( "#myDiv" ).on( "CornerstoneImageRendered", function(e) {
   // buisness logic
});

myDiv is a div which is part of angularjs component.

I want to write this listener into angularjs component. How can I do it?

PS: Event link https://github.com/cornerstonejs/cornerstone/wiki/CornerstoneImageRendered-Event


Solution

  • Create a custom directive:

    app.directive("myEventListener", function() {
        return {
            link: postLink
        };
        function postLink(scope, elem, attrs) {
            elem.on( "CornerstoneImageRendered", function(event) {
                // business logic
                scope.$eval(attrs.myEventListener, {$event: event});
                scope.$apply();
            });
        }
    });   
    

    Usage

    <div id="myDiv" my-event-listener="onMyEvent($event)">
    </div>
    

    JS

    $scope.onMyEvent = function(event) {
        console.log(event);
    };
    

    For more information, see AngularJS Developer Guide - Creating Custom Directives