AngularJS Manually Render Controller and Template

There are two ways to do this; one uses the helper directives already available (like ngInclude and ngController) and the second is manual; the manual version might be faster, but I cannot be sure.

The Easy Way:

The easy method is to simple create a new element with ngController and ngInclude attributes, append it to the directive’s element, and then $compile it:

var html="<div ng-controller=""+ctrl+'" ng-include="'+tpl+'"></div>';
element.append(html);
$compile( element.contents() )( scope );

The Manual Way:

The manual way is to do what these directives would themselves do in turn; this logic is very similar to what ngView does (though without the complexity). We fetch the template, storing it in $templateCache, and then append it to the DOM. We create a new child scope and instantiate the provided controller with it and assign that controller to the element. Finally, we $compile it:

$http.get( tpl, { cache: $templateCache } )
.then( function( response ) {
  templateScope = scope.$new();
  templateCtrl = $controller( ctrl, { $scope: templateScope } );
  element.html( response.data );
  element.children().data('$ngControllerController', templateCtrl);
  $compile( element.contents() )( templateScope );
});

(Note that there is no garbage collection here, which you would need to implement if the widgets change)

Here is a Plunker demonstrating both methods: http://plnkr.co/edit/C7x9C5JgUuT1yk0mBUmE?p=preview

Leave a Comment