6

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>
Callum Linington
  • 14,213
  • 12
  • 75
  • 154
  • What you've done will work fine, as I'm sure you're aware. Seeing as that is being deprecated in version 2.0, I really wouldn't worry about not using it for the moment as the differences between the two will be pretty significant. Also quick Google suggests that the docs are out of date, it is not being removed - https://github.com/angular/angular.js/commit/eec6394a342fb92fba5270eee11c83f1d895e9fb#commitcomment-8124407 – deadwards Jul 09 '15 at 12:14
  • @DanielEdwards oh fair enough, good shout that! I might as well put that as the answer. Or you can – Callum Linington Jul 09 '15 at 12:16
  • This is not exactly a duplicate but this question has a suitable answer: http://stackoverflow.com/questions/16496647/replace-ng-include-node-with-template – Santiago Angel Jul 20 '15 at 14:45

2 Answers2

4

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
2

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

Source

deadwards
  • 2,109
  • 1
  • 16
  • 27