Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3rd party directive inside another directive while using "controller as ... " syntax

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.

like image 642
Sagi Medina Avatar asked Oct 30 '22 23:10

Sagi Medina


1 Answers

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.

like image 107
Gábor Imre Avatar answered Nov 08 '22 14:11

Gábor Imre