I'm trying to build a directive that would do the following:
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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With