Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating an angular view

I'm making an in game UI using awesomium, at some points the game loads up and executes a chunk of javascript which is meant to create arbitrary new UI elements. e.g.

jQuery(document.body).append('<span class="game-status-alert">You Lose!</span>');

That works nicely, the problem comes when I want to create some slightly more advanced UI elements, specifically using angular. For example something like:

function ChatBoxControl($scope) { /* Stuff */ }

jQuery(document.body).append(
    '<div ng-controller="ChatBoxControl"><div ng-repeat="line in chat"><span>{{line}}</span></div></div>'
);

Not surprisingly, this does not create a new angular view. It simply adds that html to the document and never binds to the ChatBoxControl.

How can I achieve what I'm trying to do here?

like image 250
Martin Avatar asked Aug 20 '12 22:08

Martin


People also ask

Can we create component dynamically in Angular?

If we go by the Angular definition, a factory component Angular is a base class for a factory that can create a component dynamically. Instantiate a factory for a given type of component with resolveComponentFactory(). Use the resulting ComponentFactory. create() method to create a component of that type.

What is dynamic in Angular?

Dynamic means, that the components location in the application is not defined at buildtime. That means, that it is not used in any angular template. Instead, the component is instantiated and placed in the application at runtime.


1 Answers

You should $compile dynamically added angular content. Something like:

jQuery(document.body).append(
    $compile(  
        '<div ng-controller="ChatBoxControl"><div ng-repeat="line in chat"><span>{{line}}</span></div></div>'
    )(scope)
);

scope for any element you can get using something like:

var scope = angular.element('#dynamicContent').scope();

Also you should get $compile that can be injected in other controller.

See also: AngularJS + JQuery : How to get dynamic content working in angularjs

like image 180
Artem Andreev Avatar answered Oct 15 '22 05:10

Artem Andreev