0

I can't understand how to add dynamic content after click on to my HTML with a template file and some controller.

I want to something like:

element.click(function(){
  element2.html(templateUrl, controller);
});

Angular 1.5.8

Demyd Ganenko
  • 108
  • 1
  • 9
  • I recommend you read [this](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) first. Then, regarding your issue, the best would be using the [ngRoute](https://docs.angularjs.org/api/ngRoute) module: see this [example](https://docs.angularjs.org/api/ngRoute/service/$route#example). – SinDeus Feb 06 '17 at 14:14

2 Answers2

1

Although the question is not to clear I feel what you want to do is to render an html dynamically. There are two solutions for this:

  1. angular-routing: This is mostly used if you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module. The content for this is pretty readily available everywhere. You can have a look at them.
  2. custom-directive: You can try to write a directive which would render the html on whichever event you want:

    .directive("customTemplateLoad", function($http, $templateCache, $compile) {
    return {
      restrict: 'A',
      link: function(scope, element, attr, controller){
        var template;
        // Some logic to get template, perhaps pass it in the directive itself
        var templatePath = '/templates/'+template;
        $http.get(templatePath, { cache: $templateCache }).success(function(response) {
          var contents = element.html(response).contents();
          $compile(contents)(scope);
        });
      }
    };})
    
Pansul Bhatt
  • 384
  • 2
  • 5
  • I already have SPA application with angular-routing. I have some view for model Alerts and I want to add alert creation form after all alerts. – Demyd Ganenko Feb 06 '17 at 18:10
  • Perhaps something like doing document.write might help. You might find this (http://stackoverflow.com/questions/19637312/is-there-an-angular-way-of-printing-a-div-from-a-html-page) helpful. What this would do is if you have a document html ready it can insert that html for you , does this help? – Pansul Bhatt Feb 07 '17 at 07:29
0

you could create a directive with a controller and template, compile it and than add it to the DOM.

mateop
  • 94
  • 1
  • 3