[Solved] How to create reusable UI control using JavaScript [closed]


Look into javascript templating. See mustache.js for one example.

e.g.

<script type="text/template" id="template">
   {{#elements}}
      <div id="{{id}}">
         {{content}}
      </div>
   {{/elements}}
</script>

And your JavaScript:

var view = {
   "elements": 
    [
       {
          id: "one",
          content: "Lorem ipsum dolor"
       },
       {
          id: "two",
          content: "Sit amet consectetur"
       }
    ]
}

var template = document.getElementById("template").innerHTML;
var output = Mustache.render(template, view);
console.log(output);
logs:

<div id="one">
   Lorem ipsum dolor
</div>
<div id="two">
   Sit amet consectetur
</div>

You can loop through objects, evaluate functions and insert them as text.

If you use angularJS you can create a reusable html piece by making a separate html file with your component then calling it into your page as an element.

app.directive("elementName", function() {
  return {
    restrict: 'E',
    templateUrl: "/Path/To/Html.file"
  };
});

Then in every html page you want to use this component you just do the following:

<element-name></element-name>

solved How to create reusable UI control using JavaScript [closed]