0

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 () {..."

Steve
  • 14,401
  • 35
  • 125
  • 230
  • Have you considered adding it inside a directive instead of the controller? – Stryner Feb 17 '16 at 19:31
  • Your question might get more attention if you provide a [JSFiddle](https://jsfiddle.net/) or [PLNKR](http://plnkr.co/edit/?p=catalogue) showing your problem. – georgeawg Feb 18 '16 at 17:51
  • It's too difficult to re-create the set-up on one of those sites. I usually do, but this involves several external libraries etc. – Steve Feb 18 '16 at 17:52

2 Answers2

0

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • where in that directive would my code go, e.g. `log.debug('hello world')`? I tried inserting it after `scope.$apply` but no dice. – Steve Feb 18 '16 at 15:41
0

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

C-Woap
  • 21
  • 4