I have a situation where I need to compile a template with a controller instance, even though the template does not have an ng-controller directive on it. My goal is to use the supplied controller instance in the compilation process. Below is the current code snippet that I am working with:
var scope = $scope.$new();
var template = $templateCache.get('path/to/template.tpl.hml');
var controller = $controller('SomeController', {
$scope: scope,
foo: { ... },
bar: { ... }
});
var html = $compile(template)(scope);
// This part doesn't work as intended because the template lacks a controller.
scope.$apply();
The reason behind this approach: I have a form displayed within a modal using the ui-bootstrap $modal service. When calling the $modal function, I provide a template URL, a controller name, and an object containing data to be injected into the controller (refer to linked docs for more details). The $modal service handles the instantiation of the controller, data injection, template compilation, and incorporation into a Bootstrap modal dialog. Since $modal takes care of injecting dependencies into the controller, the template should not have an ng-controller attribute.
While popping up the modal works seamlessly in my application thanks to the inner workings of $modal, I encounter challenges when writing unit tests.
In my testing scenarios, I aim to manually compile the template by utilizing the $compile service. This approach allows me better access to the form's scope and DOM structure. However, achieving this has proven difficult as I haven't been able to decipher the internal processes of $modal.
Can anyone provide insights or suggestions?