1

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

6
  • I want to implement Breadcrumbs url scheme, is it possible with directives? Commented Nov 6, 2015 at 11:30
  • 3
    Yes of course you can. And someone did it ncuillery.github.io/angular-breadcrumb yet Commented Nov 6, 2015 at 11:32
  • Even if I use directives, I have to use templates and I want the templates to be created dynamically. Commented Nov 6, 2015 at 12:19
  • Are you basically asking, how to create html page dynamically. Better use template: add the html elements based on the requirement. Commented Nov 6, 2015 at 12:35
  • actually I have many items which are coming from database, and I want to create a new template for each item. Commented Nov 6, 2015 at 12:50

1 Answer 1

2

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. :)

Sign up to request clarification or add additional context in comments.

1 Comment

Even if I use directives, I have to use templates and I want the templates to be created dynamically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.