I want to dynamically load and compile a directive some time after the application is bootstrap.
Like when I press a button I want to run code similar to this:
app.directive('dynamicDirective',
['$compile', '$timeout', 'searchBuilderFactory',
function ($compile, $timeout, searchBuilder) {
return function (scope, element, attrs) {
scope.$watch(attrs.truBindNgHtml, function (newValue, oldValue) {
if (newValue === oldValue) return;
var directiveName = 'advanced' + newValue;
app.directive(directiveName, function() {
return {
template: 'Name: {{customer.name}} Address: {{customer.address}}'
};
});
var html = '<' + directiveName + '>' + '</' + directiveName + '>';
element.html(html);
$compile(element.contents())(scope);
});
};
}]);
Here is a partially working example: Fiddle
You got it almost right, I am not exactly sure about the part in the controller which does, however you have some issues.
Directive is registered fine, but restriction is a problem, you have element restriction which you need to be explicit about, i.e use restrict:'E'
When watching attributes, do not use scope.$watch
instead use attrs.$observe
, in your case attrs.$observe('dynamicDirective', fn)
, or use scope binding with scope:{dynamicDirective:'@'}
anc use scope.$watch('dynamicDirective', fn)
Inorder to pass values and have it observable use interpolation when consuming the directive while using attr or scope binding with @
, if using 2 way =
you do not need that.
Try:-
function ($compile) {
return function (scope, element, attrs) {
attrs.$observe('dynamicDirective', function (v, ov) {
if (!v) return; //If no value do nothing
var directiveName = 'advanced' + v;
app.directive(directiveName, function () {
return {
template: '<p>Blah</p>',
restrict: 'E'
};
});
var newEl = '<' + directiveName + '>' + '</' + directiveName + '>';
element.html(newEl); //or element.append(); if you want to add upon
$compile(element.contents())(scope);
});
}
}]);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments