Steve
Steve

Reputation: 14922

Using Angular Directive for multiple options

I have a site footer:

    <footer>
     <div class="container">
     <div class="contents">
      <div class="logo-copyright">
        <div class="footer-logo">
           <i class="footer-logo gradient"></i></a>
        </div>
        <div class="copyright">&copy; 2016 A Company, Inc.</div>
      </div>
      <div class="footer-terms"><a href="">Terms of use</a></div>
      <div class="footer-legal"><a href="">Legal Info</a></div>
      <div class="footer-contact"><a href="">Contact Us</a></div>
    </div>
  </div>
</footer>

I would like to put this is a directive so it can be used as something like <my-footer></my-footer>

I know how to it "as is", but my issue is that parts of this footer might not be needed in some applications. Although logo-copyright is required for everyone, its three siblings might be needed or not.

What I am looking for is a way to use the directive with options that would show the respective divs as needed for example:

<my-footer options="terms legal"></my-footer>

Would display the html with the 2 divs footer-terms and footer-legal but not footer-contact, whereas

<my-footer></my-footer>

would show the footer html with only the required logo-copyright div and omit the other 2.

I am very unclear on how to proceed in implementing this.

Upvotes: 3

Views: 46

Answers (1)

Thalaivar
Thalaivar

Reputation: 23642

I will have my directive accept three values:

<my-footer terms legal contact></my-footer>

And below would be my directive definition, i would use attrs over scope.

.directive('myFooter', function () {
    return {
        restrict: 'E',
        scope: false
        templateUrl: '/partials/footer.html',
        replace: true,
        link: function (scope, element, attrs) {
            scope.terms = typeof attrs.terms != 'undefined';
            scope.legal = typeof attrs.legal != 'undefined';
            scope.contact = typeof attrs.contact != 'undefined';
        }
    }
})

This would ensure your html part is pretty clean by ensuring only loading the components/template section of needed ones.

<my-footer terms legal></my-footer>

Would ensure only terms and legal section are loaded.

Here is a fiddle for the same: https://jsfiddle.net/spechackers/wakajwzt/

Upvotes: 3

Related Questions