AngularJS Manually Render Controller and Template

前端 未结 1 1682
醉酒成梦
醉酒成梦 2020-12-04 12:45

I\'m trying to implement a plugin system in angularjs that would allow users to configure which \"widgets\" they will see on a certain page. Each widget is defined by a con

相关标签:
1条回答
  • 2020-12-04 12:53

    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

    0 讨论(0)
提交回复
热议问题