AngularJS - how do you associate a controller by path after compiling the html?

486 Views Asked by At

Is it possible to dynamically associate a controller, after it has been compiled from a template?

//Controller /path/ctrl/MainCtrl.js
angular.module('app')
    .controller('MainCtrl', function () {

    });

//Directive  /path/dir/myDir.js
function link(scope, element, attrs) {
    $templateRequest('path/oneTpl.tpl').then(function (html) {
        $compile(element.html(html).contents())(scope);
        //How can I do to dynamically inject MainCtrl into the oneTpl.tpl template using the path (/path/ctrl/MainCtrl.js)?
    });
}
1

There are 1 best solutions below

0
On

You can try to add an attribute to your compiled template (would be good to know, what you template is exactly).

Try following code:

element.setAttribute(name, value);

Example:

<button>Hello World</button>
var b = document.querySelector("button"); 

b.setAttribute("disabled", "disabled");

So you just need a identifier of your template, e.g. id or class an then set your Attribute.

JQuery: $('#yourTemplate').setAttribute('ng-controller','yourController' );

If this doesn't help you, maybe following threads will help you:

AngularJS: dynamically assign controller from ng-repeat

Dynamic NG-Controller Name

Dynamically assign ng-controller on runtime