0

What I want to do is to load separated templates and append a controller to each one:

an approach:

$http({
    method: 'GET',
    url: 'templates/myTemplate.html',
    controller:'myCtrl'
})

function myCtrl($scope){
    $scope.var1= "scoped variable";
}

myTemplate.html:

A Tag

{{var1}}

that is an aproach to this question: Loading an AngularJS controller dynamically

Community
  • 1
  • 1
Uuid
  • 2,506
  • 5
  • 28
  • 37

1 Answers1

1

It appears that your scenario would be a good place to apply ng-include. For example, given this markup:

<div ng-controller="MainCtrl">
    <div ng-include="template"/>
</div>

and this code in MainCtrl:

function MainCtrl($scope) {
  // some logic that would determine the template you want to load
  $scope.template = 'templates/myTemplate.html';
}

and this code in templates/myTemplate.html:

<div ng-controller="TemplateCtrl">
     <!-- Template Content -->
</div>

angular will automatically download templates/myTemplate.html and apply TemplateCtrl to the template. (Of course you'd also need to have TemplateCtrl defined.) When you want to switch templates, in MainCtrl you'll need to change the value of $scope.template to another template url; that template would specify an ng-controller attribute that indicates the appropriate controller for that template.

jandersen
  • 3,551
  • 22
  • 23