Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directive property: Replace deprecated - Equivalent?

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>
like image 398
Callum Linington Avatar asked Jul 09 '15 08:07

Callum Linington


People also ask

Which directive definition option is used to replace the current element?

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.

What is link function in AngularJS?

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.

What are directives in AngularJS what is the flow of a directive?

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.


2 Answers

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.

like image 166
Estus Flask Avatar answered Oct 10 '22 23:10

Estus Flask


Docs appear to be outdated - replace for directives is not being removed.

Source

like image 38
deadwards Avatar answered Oct 11 '22 00:10

deadwards