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

211 Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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

0
On

To archive what you want first you need use

angular.element and then you can add event listener

2
On

If you're going to listen on events from an external, non angularjs, library you need to notify angularjs when a change has happend. One way to do this is by wrapping your logic, which is triggered by the external event, in the $scope.$apply method. The $apply method will notify angularjs that a change has happend and triggered the digest loop which will sync change from the scope to the view.

Add the event inside the controller and try it like this

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

Here's an great artile on the subject