20

I have been working on a angular js site, which get the data from webservice/api. One api returns html and angular js code to dynamically add conroller or whatever new angular component we want to add new. This string will come in api response

<div id="homecontainer" class="flex-center p-page" loader style="overflow:hidden;">
    <div class="column-1">
        <div class="grid m-0 col-xs-12">
            <div ng-repeat="Widget in V3Widgets track by $index" class="grid-item">
                <div class="grid-sizer"></div>
             {{Widget}}
            </div>


        </div>
        <div ng-controller="WelcomeController">
            {{greeting}}
        </div>
        <script>
            var app = angular.module('demo', [])
                //RestService is Other Module Which is Already Working fine 
            .controller('WelcomeController', function ($scope,RestService) {
                $scope.greeting = 'Welcome!';
            });
            angular.bootstrap(document, ['demo']);
        </script>
    </div>
</div>

Now i have a directive to bind this string to page

<renderdynamicwidgethtml ng-if="Widget.Id==null && Widget.Html!=null" html="Widget.Html"/>

Directive's js

.directive('renderdynamicwidgethtml', ['$compile', function ($compile) {
    return function (scope, element, attrs) {
        scope.$watch(
          function (scope) {
              return scope.$eval(attrs.html);
          },
          function (value) {
              element.html(value);
              $compile(element.contents())(scope);
          }
       );
    };
}])

scope.$eval should convert the string to angular components, but it failed with this error.

[ng:btstrpd] http://errors.angularjs.org/1.3.17/ng/btstrpd?p0=document

3
  • 2
    See following response from Jussi Kosunen
    – Alexanderp
    Commented Aug 11, 2016 at 11:50
  • Do you already have a #homecontainer?
    – Aurelia
    Commented Aug 19, 2016 at 12:43
  • How does the dynamic html look like ? It seems that it contains another ng-app and shouldn't.
    – Ioan
    Commented Aug 19, 2016 at 13:13

5 Answers 5

14

Since Angular 1.5, there's a new angular.component tool. This answer uses the word Component to make a reference to all the possible tools Angular provides (such as directives, filters, etc), including angular.component.

First let me start with the way AngularJS sets everything up:

  1. When the javascript files are loaded, you can see all the angular code starts with angular.module, angular.controller, angular.directive, etc. And all those receive a function as a parameter (except angular.module, which receives a name and a list of dependencies). At this moment, those components are not created, just registered.

  2. Once Angular has registered all the modules and components, it is ready to be bootstrapped, either with the ng-app directive or manually with angular.bootstrap. Both methods receive a string as a parameter, which is the name of the root module. Using that root module, Angular looks deeply into it's dependencies (which can be seen as a tree of dependencies), and starts loading the components from it's leaves (modules that do not have dependencies) up to the root module's components.

  3. For each module, Angular builds them in a certain order, starting from constants, then providers, then running config blocks in the order they were registered, then loading values, then factories/services, then directives and finally run blocks in the order they were registered (I'm not completely sure about the order, I suggest you double check)

  4. Finally, after everything is setup, it's 'seals' the application, so nothing else can be registered.

The error means that you are bootstraping your application twice. This can happen when using the ng-app directive and calling angular.bootstrap, or just calling angular.bootstrap more than once.

As the documentation says in the manual initialization section:

You should call angular.bootstrap() after you've loaded or defined your modules. You cannot add controllers, services, directives, etc after an application bootstraps.

So, in order to load new controllers dynamically, you should register them before the bootstrap process. You can do this by retrieving the data you need from your API (you'd need any other tool like JQuery since Angular isn't set up yet), executing the code with JavaScript's standard eval function (do this inside the request's promise), and then bootstraping AngularJS manually with angular.bootstrap.

For this to work, the code you execute with eval should be purely javascript, I recommend separating it from the HTML either by changing the API's response (if possible), or doing it programmatically after getting the response.

Also, if you need to do this more than once, make sure that the code execute with eval doesn't bootstrap Angular before registering all the components you need.

1
2

Why are you using scope.$eval instead of $compile service which is intended to compile your template string.

   link: function (scope, ele, attrs) {
      scope.$watch(attrs.html, function(html) {
        $compile(ele.contents())(scope);
      });
    }
2

Try this:

    app.directive('dynamic', [ '$compile',
function ($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, ele, attrs) {
            scope.$watch(attrs.dynamic, function (html) {
                ele.html(html);
                $compile(ele.contents())(scope);
            });
        }
    };
}]);

You could put the entire string in $scope.myString in your js, and in your HTML <div dynamic="myString"></div>. It should compile and render everything.

0

I've found a possible solution where I don't need to know about the controller before bootstrapping:

// Make module Foo and store $controllerProvider in a global
var controllerProvider = null;
angular.module('Foo', [], function($controllerProvider) {
    controllerProvider = $controllerProvider;
});
// Bootstrap Foo
angular.bootstrap($('body'), ['Foo']);

// .. time passes ..

// Load javascript file with Ctrl controller
angular.module('Foo').controller('Ctrl', function($scope, $rootScope) {
    $scope.msg = "It works! rootScope is " + $rootScope.$id +
        ", should be " + $('body').scope().$id;
});
// Load html file with content that uses Ctrl controller
$('<div id="ctrl" ng-controller="Ctrl" ng-bind="msg">').appendTo('body');

// Register Ctrl controller manually
// If you can reference the controller function directly, just run:
// $controllerProvider.register(controllerName, controllerFunction);
// Note: I haven't found a way to get $controllerProvider at this stage
//    so I keep a reference from when I ran my module config
function registerController(moduleName, controllerName) {
    // Here I cannot get the controller function directly so I
    // need to loop through the module's _invokeQueue to get it
    var queue = angular.module(moduleName)._invokeQueue;
    for(var i=0;i<queue.length;i++) {
        var call = queue[i];
        if(call[0] == "$controllerProvider" &&
           call[1] == "register" &&
           call[2][0] == controllerName) {
            controllerProvider.register(controllerName, call[2][1]);
        }
    }
}
registerController("Foo", "Ctrl");
// compile the new element
$('body').injector().invoke(function($compile, $rootScope) {
    $compile($('#ctrl'))($rootScope);
    $rootScope.$apply();
});

Fiddle. Only problem is that you need to store the $controllerProvider and use it in a place where it really shouldn't be used (after the bootstrap). Also there doesn't seem to be an easy way to get at a function used to define a controller until it is registered, so I need to loop through the module's _invokeQueue, which is undocumented.

UPDATE: To register directives and services, instead of $controllerProvider.register simply use $compileProvider.directive and $provide.factory respectively. Again, you'll need to save references to these in your initial module config.

UDPATE 2: Here's a fiddle which automatically registers all controllers/directives/services loaded without having to specify them individually.

0
+50

You can use javascript eval for eval js code and $compile for the html code. I have setup a plunker with complete test code. here is the link.

https://plnkr.co/edit/9sJw8ua1n5ItnHONwGmS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.