UPDATE: All directives listed below will now require ng-model bindings to be applied in the elements they generate, targeting the controller assigned to the page. The code has been modified to reflect this.
I am exploring the creation of dynamic HTML using directives. Initially, a basic scenario worked well with a single directive, but as I attempt a more complex setup, I am unsure of the approach. Imagine an HTML page with existing content, followed by a declaration like this at the end:
<div directiveOne></div>
The directiveOne successfully compiles and adds extra elements to the page. Now, my goal is for directiveOne to add those same elements, along with an additional one that itself uses another directive. When expanded, it should resemble something similar to the following example:
<div directiveOne>
<input type='text'/>
<div directiveTwo>
<select>
<option>Option</option>
</select>
</div>
</div>
The reason for having multiple directives is to execute specific code to determine the appearance of the elements. Ultimately, I aim for directiveOne to leverage several mini-directives, not just directiveTwo.
Currently, here are the simplified versions of the two directives for clarity:
angular.module('myApp').directive('directiveOne', function ($compile) {
return {
restrict: 'EAC',
scope: false,
templateUrl: '/basePage.html',
compile: function(element, attr) {
var jsonObj = { test: 'TestData' };
return function(scope, element, attr) {
var elem = "<div directiveTwo='"+jsonObj+"'></div>";
$compile(elem)(scope);
element.append(elem);
}
}
};
});
angular.module('myApp').directive('directiveTwo', function ($compile) {
return {
restrict: 'EAC',
scope: false,
templateUrl: '/subPage.html',
compile: function(element, attr) {
return function(scope, element, attr) {
// Make changes to subPage.html if needed
var elem = "<input ng-model='scopedControllerVar'>";
$compile(elem)(scope);
element.append(elem);
}
}
};
});
Partially successful, inspecting the resulting HTML reveals:
<div directiveOne>
<div directiveTwo="[object Object]"></div>
</div>
However, the code within directiveTwo did not execute, rendering the div empty. Is there a way to achieve this functionality?