Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird ngIf + $compile behavior

I'm trying to build a directive that would do the following:

  • add another directive to the element (ngSwipeRight for example)
  • add some custom behavior to the new directive.

An example would be: mySwipeBack that would add ngSwipeRight and when the user swipes over the element I would do history.back().

I tried like this:

.directive('swipe', function($compile){
  return {
    restrict: 'A',
    compile: function(el){
        // I removed all the actual logic for demo purposes
        // here I would add ng-swipe-right plus a handler
        el.removeAttr('swipe');
        var fn = $compile(el);
        return function (scope) {
          fn(scope);
        };
   }
 }
});

But I ran into an issue with the following markup:

<div ng-if='true'>
  <h1 swipe>OUTSIDE
    <div ng-if="true">INSIDE</div>
  </h1>
</div>

The "INSIDE" text doesn't get rendered. You can see the behavior in this jsbin: http://jsbin.com/tokofevuga/edit?html,js,output

If I remove the first ng-if, it works as intended.

Does anyone know what the reason is behind this - and if I can make it work?

Or if someone has another idea of how to achieve what I described above?

like image 492
sirrocco Avatar asked Apr 27 '17 03:04

sirrocco


People also ask

What does ngIf mean?

A shorthand form of the directive, *ngIf="condition" , is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.

What is * ngIf in HTML?

Definition and Usage. The ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.

Does ngIf work on Div?

The Angular ngIf directive works essentially as an if statement for HTML, adding this missing feature to the language under the form of the special ngIf attribute. In this example, the container div will only be shown to the user if the user is logged in, otherwise the whole content of the div is not visible.

What does $compile do in AngularJS?

The $compile service is the service to use for compilation. Invoking $compile against markup will produce a function you can use to bind the markup against a particular scope (what Angular calls a linking function). After linking, you'll have DOM elements you can place into the browser.


1 Answers

    return function (scope) {
      $compile(el)(scope);
    };

Work for me ... And the point is that in your code - you compile element immediately in directive compile, while here function is returned from compile, that will be executed somewhen later.

like image 138
Petr Averyanov Avatar answered Oct 08 '22 08:10

Petr Averyanov