Johnny000
Johnny000

Reputation: 2104

AngularJS load tabbed content directive dynamicly

I have a tabbed navigtion in my webapp that looks like this enter image description here

Now I want to Change the directive each time the user clicks on one of the Navigation points. My Idea was to init the page with the first template.

$scope.currentDirective = $compile('<div order-Sale></div>');

Then when the user clicks on a tab, I wanted to change and compile the content again with a new directive in it. But for some reason this is not working. How would you proceed in order to archive this dynamic content loading? I really want to only load the content on necessary need and not just to show or hide it. I think using directives is the right way to go for it, but I'm a but stuck at the implementation... Someone any pointer ? (I don't want to use any jQuery)

What I tried [Edit]:

The controller.js

    app.controller('pageController',['$scope','$compile', function($scope, $compile){

      var templates = ['<div first-template></div>','<div second-template></div>'];

      $scope.currentTemplate = $compile(templates[0]);

      $scope.changeTemplate = function(id) {

        $scope.currentTemplate = $compile(templates[id]);

      };

  }]);

The HTML

<div ng-controller="pageController">
    <li>
        <a ng-click="changeTemplate('1')">Change Template</a>
    </li>
    {{currentTemplate}}
</div>

Upvotes: 1

Views: 2869

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32397

UPDATE

Here is a plunker

  app.controller('pageController',['$scope','$compile','$sce', function($scope, $compile, $sce){
    var templates = ['<div>first-template</div>','<div>second-template</div>'];
    $scope.currentTemplate = $sce.trustAsHtml(templates[0]);
    $scope.changeTemplate = function(id) {
      $scope.currentTemplate = $sce.trustAsHtml(templates[id]);
    };
  }]);

The markup:

  <div ng-controller="pageController">
    <button ng-click="changeTemplate('1')">Change Template</button>
    <div ng-bind-html="currentTemplate"></div>
  </div>

For more robust dynamic content loading you have two good alternatives:

If you want to change and compile the content again, well that's exactly what ng-view/ ui-view directives already do for you.

Why not just use a directive:

  • You probably need to load a different template (html partial) for each tab.
  • You probably need to change the url based on the tab (and vice versa)
  • You probably need to instantiate a different controller for each tab.
  • ngRoute and ui-router come with their own directives.
  • You can implement your own route module if you want but that's more than just a directive.

Upvotes: 1

Related Questions