Angular JS controller detect third-party event?

564 Views Asked by At

I have an Angular 1.4.9 app. I'm using a third party JS plugin (Jasny Bootstrap). It has some JS components, which appear to use simple JQuery.

Their docs say that the plugin emits events at key points, such as "itemShown". I was wondering if I can detect this in my page's controller and act upon it, as in:

"on itemShown function () {..."

2

There are 2 best solutions below

1
On

If you embed jQuery in your app (because Angular embeds jQlite by default, but not jQuery), here is one solution.

You can do it from the controller, after your element is ready:

$element.ready(function () {
    $('#offcanvasId').on('hide.bs.offcanvas', function(){
        //...
    })
});

Nonetheless, there must be some workarounds without jQuery.

You can see more on the documentation https://docs.angularjs.org/api/ng/function/angular.element

1
On

Handling Custom jQuery Events in AngularJS

The following example shows a custom directive that detects a custom jQuery events and invokes a function defined by an attribute.

app.directive("onBsShowOffcanvas", function($parse) {
    return function linkFn(scope, elem, attrs) {
        var fn = $parse(attrs.onBsShowOffCanvas);
        elem.on("show.bs.offcanvas", function(e) {
            fn.assign(scope, {$event: e});
            scope.$apply();
        });
    }
});

To use the directive in your HTML:

<div on-bs-show-offcanvas="offcanvasHandler($event)">

I recommend that the event object be exposed as $event since that is customary with AngularJS event directives.

$event

Directives like ngClick and ngFocus expose a $event object within the scope of that expression. The object is an instance of a jQuery Event Object when jQuery is present or a similar jqLite object.

-- AngularJS Developer Guide -- $event