Sombir Kumar
Sombir Kumar

Reputation: 1881

create dynamic template in angularjs

Hi I want to create angular template dynamically like below:

Index.html:

    <div ui-view></div>
    <ul class="nav-links">
       <li ng-repeat="item in items">
           <a ui-sref="{{item.id}}"">{{item.name}}</a>
       </li>                    
    </ul>

    <script ng-repeat="item in items" type="text/ng-template" id="{{item.id}}.html">
     <h1>{{item.name}}</h1>
    </script>

How could I do that? I searched on web and found that we can include template dynamically, but I did not find any place where it is specified that how to create template itself dynamically.

Thanks, Sombir

Upvotes: 1

Views: 547

Answers (1)

The best way you can do that is Custom Directives! it is what makes angularjs powerfull.

.directive('myCustomer', function() {
  return {
    restrict: 'E',
    template: 'myCustomer.html'
  };
});

and in your index or whatever you can call it:

<my-customer></my-customer>

EDIT: To generate dynamicaly your Custom directive Use the property Controller or Link.

.directive('myCustomer', function() {
  return {
    restrict: 'E',
    template: 'myCustomer.html',
    controller: function ($scope,$http) {
     // here you can use $scope, $http etcs... but
    }, // to make it clean and standard use Link
    link: function (scope, element, attrs) {
      // do all stuff like API call JQuery stuff and all here
    }
  };
});

with that you can generate dynamicaly you directive :) from an API or whatever you want to. :)

Upvotes: 2

Related Questions