Search code examples
angularjsangularjs-directiveangularjs-scope

AngularJS - Accessing the controller of a third party directive


I'm trying to use the Search-Filter from the UI Framework LumX in what I admit is not traditional use.

The intended way the filter works is you press the magnifying glass button, it opens; calls method openInput on the controller. The mouseout click closes it.

However I wish to extend this by opening and closing the input upon clicking on the toolbar__label span but my Angular knowledge is just not up to par yet.

My HTML looks like

<div class="toolbar" opensearch>
  <span class="toolbar__label fs-title ml black__text" >{{ "content.search.tip" | translate }}</span>
  <div class="toolbar__right">
    <lx-search-filter lx-width="400" lx-closed="true" >
      <input type="text" ng-model="vm.searchFilter.third">
    </lx-search-filter>
    <button class="btn btn--l btn--black btn--icon" lx-ripple>
      <i class="mdi mdi-apps"></i>
    </button>
  </div>
 </div>

If you open the github link, the ng-click of the directive itself is

ng-click="lxSearchFilter.openInput()"

My question is how can I access this lxSearchFilter controller from outside of the lx-search-filter directive?

I added my own directive opensearch and using the good old jquery way of things I can get it to work like:

link: function(scope, element) {
  element.bind('click', function(e) {
    var btn = angular.element(e.target).parent().find('button')[0];
    if (!isOpen) {
        isOpen = true;
        angular.element(btn).trigger('click');
      }
      return false;
    });

This does work with two caveats:

1. After a single open/close action I cannot reopen it
2. It's not the Angular way??

So again my question is how can I access this lxSearchFilter controller from outside of the lx-search-filter directive?


Solution

  • You can access the controller/link function of 3rd party directives by using decorator

    https://docs.angularjs.org/guide/decorators

    You can use .decorator like .controller and put the code of $provide.decorator in the example inside it.


    Edit: The way is to use decorator to extend it to support programatically open/close the search

    https://jsbin.com/siceyeqeza/edit?html,js,output

    Note that changing $delegate[0].scope only works when you have angular > 1.5.1 due to a bug https://github.com/angular/angular.js/issues/14785