AngularJS: how to transclose and replace containing element

I am trying to create a set of AngularJS directives that will conditionally display mutually exclusive segments of block or inline page content. For example, I am assuming a mechanism that will only display the nth child:

<selector member="index"> <div>This div is visible when $scope.index equals 0</div> <div>This div is visible when $scope.index equals 1</div> <div>This div is visible when $scope.index equals 2</div> </selector> 

However, my project requires that the directives be implemented using special markup of elements (not attributes that apply to HTML elements), and that these HTML invalid elements are removed from the DOM when rendering is complete. Thus, in the above example, there will be one div matching element.

As a first attempt to prototype this concept, I converted the ngIf built-in directive to use the following element-based syntax:

 <if condition="true"> <p>This is visible</p> </if> <if condition="false"> <p>This is not visible</p> </if> 

To do this, simply change the restrict to E and change the name of the observed attribute to condition . Here is my modified version of the inline implementation:

 application.directive("if", ['$animate', function ($animate) { return { transclude: 'element', priority: 1000, terminal: true, restrict: 'E', compile: function (element, attr, transclude) { return function ($scope, $element, $attr) { var childElement; var childScope; $scope.$watch($attr.condition, function (value) { if (childElement) { $animate.leave(childElement); childElement = undefined; } if (childScope) { childScope.$destroy(); childScope = undefined; } if (toBoolean(value)) { childScope = $scope.$new(); transclude(childScope, function (clone) { childElement = clone; $animate.enter(clone, $element.parent(), $element); }); } }); }; } }; }]); 

However, I don't have much success eliminating the containing if element. I suspect that I need a much better understanding of how transclusion is designed to work, but there seems to be not much documentation.

So, if you could either suggest the right technique for use, or point me towards some relevant textbooks, I would really appreciate it.

Thanks Tim

+4
source share
1 answer

Doesn't replace what you want?

  transclude: 'element', priority: 1000, terminal: true, restrict: 'E', replace: true, // ** // 

This will replace if with content

+3
source

Source: https://habr.com/ru/post/1501084/


All Articles