Note that there are some explanatory texts on larger screens.

plurals
  1. POReuse angular directives within other directives
    text
    copied!<p>I would like to lazy load images and iframes (i.e. set the src once the element is in the viewport). I have an existing angular directive <code>is-visible</code> that sets the <code>is-visible</code> attribute when an element scrolls into view. How do I reuse this directive from within my <code>set-src-when-visible</code> directive?</p> <p>i.e., I want this code to reuse the <code>is-visible</code> directive:</p> <pre><code>&lt;img set-src-when-visible="http://example.com/img.png" /&gt;` &lt;iframe set-src-when-visible="http://example.com/" /&gt; </code></pre> <hr> <h3>Unsatisfactory approach 1: Require <code>is-visible</code> directive</h3> <p>I can require the <code>is-visible</code> directive to be on the same element I am declaring the <code>set-src-when-visible</code> directive on:</p> <pre><code>&lt;img set-src-when-visible="url" is-visible /&gt; myApp.directive('setSrcWhenVisible', function () { return { restrict: 'A', require: 'isVisible', link: function ($scope, element, attrs) { var set = false; attrs.$observe('isVisible', function(isVisible) { if(isVisible &amp;&amp; !set) { attrs.$set('src', $scope.$eval(attrs.setSrcWhenVisible)); set = true; } }); } } }); </code></pre> <p>Here is a working example: <a href="http://jsfiddle.net/pvtpenguin/6tCk6/" rel="nofollow">http://jsfiddle.net/pvtpenguin/6tCk6/</a></p> <p><strong>Downside:</strong> I'd like to be able to specify only the <code>set-src-when-visible</code> directive while still reusing <code>is-visible</code>.</p> <hr> <h3>Unsatisfactory approach 2:</h3> <p>Create two directives, one for iframe and one for img tag:</p> <pre><code>&lt;iframe set-iframe-src-when-visible="url"&gt;&lt;/iframe&gt; &lt;img set-img-src-when-visible="url" /&gt; angular.forEach(['Iframe', 'Img'], function(tagName) { var directiveName = 'set' + tagName + 'SrcWhenVisible'; myApp.directive(directiveName, function ($window) { return { restrict: 'A', template: '&lt;' + tagName + ' is-visible&gt;&lt;/' + tagName + '&gt;', replace: true, link: function ($scope, element, attrs) { var set = false; attrs.$observe('isVisible', function(value) { if(value &amp;&amp; !set) { attrs.$set('src', $scope.$eval(attrs[directiveName])); set = true; } }); } } }); }); </code></pre> <p>Working example: <a href="http://jsfiddle.net/pvtpenguin/K4JuC/2/" rel="nofollow">http://jsfiddle.net/pvtpenguin/K4JuC/2/</a></p> <p><strong>Downside</strong>: different names for each directive, plus this doesn't fit well with the method I am using to declare and configure my app.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload