programmer
programmer

Reputation: 1094

AngularJS how to recompile a dynamically loaded directive

I've been messing around with this all morning to isolate my problem. I am dynamically loading a directive by name when my page loads. Now I want to be able to change that dynamically loaded directive based on a select option.

A link to my Plunker is below. It is properly loading the data I need but it's not switching out the directive. I'm guessing I need to do some sort of recompile but I don't know where to begin.

http://plnkr.co/edit/DSEFDlVorNymwVwk1riK?p=preview

Here is the JavaScript part of my code:

  (function(angular) {
  'use strict';

  var myAppModule = angular.module('myApp', []);

  myAppModule.controller('myController', function($scope) {

    $scope.directives = [{
      id: 'my-directive1',
      label: 'My Directive1',
      data: 'Directive 1 data.'
    }, {
      id: 'my-directive2',
      label: 'My Directive 2',
      data: 'Directive 2 data.'
    }];

    $scope.selectedDirectiveId = $scope.directives[0].id;
    $scope.selectedDirectiveData = $scope.directives[0].data;

    $scope.selectChanged = function() {
      for (var i = 0, len = $scope.directives.length; i < len; i++) {
        if ($scope.directives[i].id == $scope.selectedDirectiveId) {
          $scope.selectedDirectiveId = $scope.directives[i].id;
          $scope.selectedDirectiveData = $scope.directives[i].data;
          break;
        }
      }
    };
  });

  myAppModule.directive('loaddirective', function($compile) {
    return {
      restrict: 'A',
      scope: {
        loaddirective: "=",
        directivedata: "="
      },
      link: function($scope, $element, $attr) {
        var value = $scope.loaddirective;
        if (value) {
          $element.html("<div " + value + " directivedata='directivedata'></div>");
          $compile($element.contents())($scope);
        }
      },
      controller: ['$scope',
        function($scope) {
        }
      ]
    };
  });

  myAppModule.directive('myDirective1', function() {
    return {
      templateUrl: 'my-directive1.html',
      scope: {
        directivedata: "="
      }
    };
  });

  myAppModule.directive('myDirective2', function() {
    return {
      templateUrl: 'my-directive2.html',
      scope: {
        directivedata: "="
      }
    };
  });

})(window.angular);

Upvotes: 0

Views: 1434

Answers (1)

Jerry
Jerry

Reputation: 1026

Just listen to change and update it. http://plnkr.co/edit/NuSOA64QJ5Qro3L72zzZ?p=preview

  link: function($scope, $element, $attr) {
    console.log('loaddirective link');
    var value = $scope.loaddirective;

    function update (value) {
      $element.html("<div " + value + " directivedata='directivedata'></div>");
      $compile($element.contents())($scope);
    }
    if (value) {
      update (value);
    }
    $scope.$watch('loaddirective', update);
  },

Upvotes: 3

Related Questions