How to use the replace function for custom AngularJS directives?

Why don't replace=true or replace=false affect the code below?

Why is "some existing content" not displayed when replace = false?

Or, if you come to terms, can you kindly explain what replace=true/false in directives and how to use it?

Example

JS / Angular:

 <script> angular.module('scopes', []) .controller('Ctrl', function($scope) { $scope.title = "hello"; }) .directive('myDir', function() { return { restrict: 'E', replace: true, template: '<div>{{title}}</div>' }; }); </script> 

HTML:

 <div ng-controller="Ctrl"> <my-dir><h3>some existing content</h3></my-dir> </div> 

See here at Plunker:

http://plnkr.co/edit/4ywZGwfsKHLAoGL38vvW?p=preview

+89
angularjs angularjs-directive
Mar 19 '14 at 6:11
source share
2 answers

When you have replace: true , you get the following DOM fragment:

 <div ng-controller="Ctrl" class="ng-scope"> <div class="ng-binding">hello</div> </div> 

whereas replace: false you get the following:

 <div ng-controller="Ctrl" class="ng-scope"> <my-dir> <div class="ng-binding">hello</div> </my-dir> </div> 

Thus, the replace property in directives refers to whether the element to which the directive applies ( <my-dir> in this case) ( replace: false ), and the directive template should be added as your child,

OR

the element to which the directive applies must be replaced ( replace: true ) with the directive template.

In both cases, the element (to which the directive applies), children will be lost. If you want to transfer the original content / children of an element, you will have to translate it. The following directive will do this:

 .directive('myDir', function() { return { restrict: 'E', replace: false, transclude: true, template: '<div>{{title}}<div ng-transclude></div></div>' }; }); 

In this case, if you have an element (or elements) with the ng-transclude attribute in the directive template, its content will be replaced by the element (to which the directive applies) the original content.

See example transition http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this one to learn more about closing.

+186
Mar 19 '14 at 6:30 a.m.
source share

replace:true deprecated

From Documents:

replace ([DEPRECATED!], will be removed in the next major release - that is, v2.0)

indicate that the template should replace. The default is false .

  • true - the template will replace the directive element.
  • false - the template will replace the contents of the directive element.

- AngularJS Comprehensive Directive API

From GitHub:

Caitp - It is deprecated because there are known, very stupid issues with replace: true , some of which cannot really be fixed in a reasonable way. If you are careful and avoid these problems, then you have more energy, but for new users it’s easier to just say to them: "This will give you a headache, do not do this."

- Problem with AngularJS No. 7636

+32
Feb 20 '16 at 4:41
source share



All Articles