Devin Dixon
Devin Dixon

Reputation: 12363

Updating A Directive's Template AngularJS

In AngularJS directive, directives have a template like so:

app.directive('exampleDirective', ['$http',
function($http) {

    return {
        restrict : 'A',
        template : '<div>Example Template Content</div>',
        link : function(scope, element, attrs, controller) {
        }
    };
}]);

Is there a way of dynamically changing the template based upon actions that occur, such a click changing the directive template?

Upvotes: 1

Views: 65

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32357

You have lots of options depends on what you need, plunker:

app.directive('mydir',function($compile){
  return {
    restrict : 'A',
    template : '<div>Example Template Content</div>',
    link : function(scope, element, attrs, controller) {

      var newTemplate = "<div>changed</div>";

      // if you need to compile:
      newTemplate = angular.element(newTemplate);
      $compile(newTemplate)(scope);

      element.on('click', function(){
        element.empty();
        element.append(newTemplate)
      });
    }    
  }
})

If you can be more specific I'll give more examples.

Upvotes: 2

Related Questions