I have a custom directive <my-configform></my-configform> in which I get a JSON array from an API during the compile stage and dynamically construct the element's DOM from:
angular.module('mymodule').directive('myConfigform', function($http, $compile, $interpolate) {
restrict: 'E',
controller: 'ConfigCtrl', // Added as per Craig's suggestion
compile: function(element) {
var buildMyForm = function(data) {
var template = $interpolate('<form role="form">{{form}}</form>');
var formMarkup;
// ... build formMarkup from data ...
// just as a very simple example what it could look like:
formMarkup = '<input type="checkbox" ng-model="config.ticked"> Tick me';
return template({form: formMarkup});
};
$http.get('/api/some/endpoint').success(function(data) {
element.replaceWith(buildMyForm());
});
}
});
My problem is that the form is not bound to the controller after compilation. The elements are all in the DOM, but the no data binding has taken place.
How can I tell Angular to bind the controller to my dynamically created form?ConfigCtrl controller is not created and
You need to compile the generated html inside the post linking function like below:
.directive('myConfigform', function($http, $compile, $interpolate) {
return {
restrict: 'E',
compile: function(element) {
var buildMyForm = function(data) {
var template = $interpolate('<form role="form">{{form}}</form>');
var formMarkup = '<input type="checkbox" ng-model="config.ticked"> Tick me';
return template({form: formMarkup});
};
element.replaceWith(buildMyForm());
return function(scope, element) {
$compile(element.contents())(scope);
};
}
};
});
Here is a working plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With