So AngularJs
are deprecating the Replace
property of a directive. reference
context:
.directive('myDir', function($compile) {
return {
restrict: 'E',
template: '<div>{{title}}</div>'
}
});
this will ouput:
<my-dir>
<div> some title </div>
</my-dir>
So, Replace
would replace <my-dir></my-dir>
with the template
. What is the equivalent these days? Or is it just to use a directive with restrict: 'A'
.
I created this:
.directive('myDir', function($compile) {
return {
restrict: 'E',
template: '<div>{{title}}</div>',
link: link
};
function link(scope, iElem, IAttr, ctrl, transcludeFn) {
var parent = iElem.parent();
var contents = iElem.html();
iElem.remove();
parent.append($compile(contents)(scope));
}
});
which will output:
<div> some title </div>
As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically.
link function is basically used to manipulate the DOM( Document Object Model ) element using custom directive. link option in custom directive registers DOM listener and also update the DOM. Watch the live demo or download code from the link given below.
To put it simply, directives are JavaScript functions that manipulate and add behaviors to HTML DOM elements. Directives can be very simplistic or extremely complicated.
Basic equivalent to replace: true
is
app.directive('directive', function () {
return {
...
link: function postLink(scope, element, attrs) {
element.replaceWith(element.contents());
}
};
});
However, there are side effects that you can easily spot. Bindings are still there but attributes from the directive won't be translated into the template.
Luckily, there is usually no reason for this unless conditional replace
is required. replace
is considered deprecated for Angular 2 as you already noticed (it doesn't fit into web components concepts) but is perfectly fine for 1.x.
Docs appear to be outdated - replace
for directives is not being removed.
Source
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