Skip to content Skip to sidebar Skip to footer

Load Component Programmatically In Angular 1.6

I have an AngularJS 1.6 application which has a widget section. The widget section is a row with 3 widget that the end user can configure himself. He's given a list of all availabl

Solution 1:

As I suggested in the comments section, you can use a module-slot directive and input the module as a sort of model, and internally resolve either the loading and compilation of the desired module.

This solution uses ocLazyLoad but you can use other loader if you want.

I've made a fork of your plunkr with a solution using ocLazyLoading

So, instead of declaring all modules and control its visibility with ng-if you use only one directive like so:

<divclass="row"><divclass="col-xs-4"><module-slotmodule="c.firstModule"></module-slot></div><divclass="col-xs-4"><module-slotmodule="c.secondModule"></module-slot></div><divclass="col-xs-4"><module-slotmodule="c.thirdModule"></module-slot></div></div>

Directive:

angular.module("app")
    .directive('moduleSlot', function($ocLazyLoad, $compile) {
      return {
        restrict: 'E',
        scope: {
          module: '='
        },
        link: function(scope, element, attrs) {
          // watch the module change
          scope.$watch('module', function() {
            // load the module
            $ocLazyLoad.load("module" + scope.module + ".js").then(function() {
              // compiles the new component inside the slot
              element.html("<module-" + scope.module + "></module-" + scope.module + ">");
              $compile(element.contents())(scope);

            }, function(e) {
              console.log('errr');
              console.error(e);
            })
          });
        }
      }
    });

Refs

OcLazyLoad Docs

Simple Example from ocLazyLoad repository

$compile service docs

Solution 2:

Here a plunker showing a solution. The key is to create a directive to associate template and controller dynamicly

app.directive("module", ['$compile', '$http', '$controller', '$templateCache', function ($compile, $http, $controller, $templateCache) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            model: '='
        },
        link: function (scope, element, attrs) {
            scope.$watch("model", function (newValue, oldValue, scope) {
                if (newValue) {
                    var template = scope.model.id + ".html";
                    $http.get(template, { cache: $templateCache }).then(function (result) {
                        element.html(result.data);
                        element.children().data('$ngControllerController', $controller(scope.model.id + "Ctrl", { $scope: scope }));
                        $compile(element.contents())(scope);
                    });
                }
            });
        }
    };
}]);

Post a Comment for "Load Component Programmatically In Angular 1.6"