5

This is code snippet that recreates my problem:

html:

...
<div ng-controller="worker as workerCtrl">
    <my-directive label="label" controllerAs="workerCtrl" function="fileUpload(e, this.options)"></my-directive> 
</div>

controller:

...
function fileUpload(file, options){...}
...

directive:

function myDirective($compile) {

    var directive = {
        restrict: 'E',
        link: link
    };
    return directive;

    function link(scope, element, attrs) {
        var htmlText = '<lx-file-input ' +
            'change="'+attrs.controllerAs+'.'+attrs.uploadFunction+'" ' +
            'label="'+attrs.label+'"></lx-file-input>';
        element.replaceWith($compile(htmlText)(scope));
    }
}

Should be: ('lx-file-input' is a 3rd party directive...)

<lx-file-input change="workerCtrl.fileUpload(e, this.options)" label="someLabel"</lx-file-input>

The problem is that the timing of Angular compiling and linking is off, and the templates is left with HTML string instead of the compiled function. I know it will work if i will set the controller inside the directive but I want it to use the same function in the same 'workerCtrl' scope from the HTML.

Sagi Medina
  • 915
  • 1
  • 9
  • 11

2 Answers2

1

First you can try to pass the function from the outside like the on-close in the official Angular guide.

<div ng-controller="Controller">
  {{message}}
  <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog(message)">
    Check out the contents, {{name}}!
  </my-dialog>
</div>

But I don't see why you should not create a bridge function in the scope of your directive that calls on to the desired function. I'd prefer this way.

Recently I had almost the same answer as you have just posted. You may find other useful posts there too.

Community
  • 1
  • 1
Gábor Imre
  • 5,899
  • 2
  • 35
  • 48
  • //HackMagicDragonsBeHere What about a horrible 2-step instantiation? Creating a temporary directive that parses the controller function and replaces itself with a directive that actually brings in the 3rd party directive. :D Just wondering whether it would work... – Gábor Imre Jul 17 '15 at 23:12
1

I have posted my solution here: https://github.com/formly-js/angular-formly-templates-lumx/issues/12#issuecomment-126464833

Sagi Medina
  • 915
  • 1
  • 9
  • 11