AngularJS Manually Render Controller and Template -


i'm trying implement plugin system in angularjs allow users configure "widgets" see on page. each widget defined controller , template(url). possible create directive instantiates controller, invokes template , transcludes resulting content?

the goal this:

<div class="widget" ng-repeat="widget in widgets">     <widget controller="widget.controller" templateurl="widget.templateurl"></widget> </div> 

there 2 ways this; 1 uses helper directives available (like nginclude , ngcontroller) , second manual; manual version might faster, cannot sure.

the easy way:

the easy method simple create new element ngcontroller , nginclude attributes, append directive's element, , $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 these directives in turn; logic similar ngview (though without complexity). fetch template, storing in $templatecache, , append dom. create new child scope , instantiate provided controller , assign controller element. finally, $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 there no garbage collection here, need implement if widgets change)

here plunker demonstrating both methods: http://plnkr.co/edit/c7x9c5jguut1yk0mbume?p=preview


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -