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

3
  • Could you clarify your question and explain what you are trying to achieve? Give an example of the expected result if possible. Commented Aug 15, 2013 at 23:09
  • i've just edited the question. Commented Aug 15, 2013 at 23:21
  • You can add the ng-controller directive to any element once it's part of the DOM. Commented Aug 16, 2013 at 0:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great!, I guess this is the way to go!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.