Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I would like to leverage AngularJS' directives to create a custom control that can be plugged into a website. Something like this, consuming site that wants the control adds a script tag, a data attribute and a special tag as follows:

<script src="0. SCRIPT REFERENCE TO OUR LIB" ></script>
<div>
   <h1>Some content here</h1>
   <magic-product data-product-id="1. PRODUCT HERE" />
</div>

So the source would look like this

<script src="http://fooservice.com/1/angularscriptstuff.js"></script>
<div>
   <h1>Some content here</h1>
   <magic-product data-product-id="4" />
</div>

And would render, like this once that script has loaded

<script src="http://fooservice.com/angularscriptstuff.js"></script>
<div>
   <h1>Some content here</h1>
   <div>
      <h2>Magic Shoes</h2>
      <p>These shoes are awesome (Product 4)</p>
      <a href="http://fooweb.com/products/4">Buy now!</a></a>
   </div>
</div>

If the page owner doesn't like the default template (that's provided courtesy of the script) they can specify their own:

<script src="http://fooservice.com/angularscriptstuff.js"></script>
<div>
   <h1>Some content here</h1>
   <div>
      Have you seen this: 
      <a href="{{ product.url }}">{{ product.title }}</a>
   </div>
</div>

Which renders

<script src="http://fooservice.com/angularscriptstuff.js"></script>
<div>
   <h1>Some content here</h1>
   <div>
      Have you seen this:
      <a href="http://fooweb.com/products/4">Magic Shoes</a></a>
   </div>
</div>

Obviously, the coupling removes the onus from the owner of the source on providing the template but can override with their own template as necessary. Is this possible? What is the best way to create such a directive?

Specifically, I'm unclear how one would

  • encapsulate all this behavior in the addition of a script tag and a custom element.
  • have a default, overridable template.
  • finally, how to avoid any collisions with angular that may be in use on the host site.
share|improve this question
    
Have you considered reading the anguar documentation about directives, which has pages and pages explaining how to implement them? docs.angularjs.org/guide/directive. Is there something specific you don't understand in this documentation? Because your question basically asks us to regurgitate the directive documentation, and doesn't show any attempt at implementing anything. –  JB Nizet yesterday
    
I read the docs, of course. I added some more clear questions at the end. –  ConfusedNoob 16 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.