7

I have a situation where I have one Angular controller, which basically just loads html templates depending on a click event. However, these templates are governed by there own controllers. This results in a controller being inside the original controller, which seems just wrong:

<div ng-controller="WindowCtrl" id="focus-window">

    <button ng-click="openProjects()">Show Projects</button>
    <button ng-click="openTasks()">Show Tasks</button>
    <div ng-include src="template.url"></div>

</div>

controllers.js

.controller('WindowCtrl', function ($scope) {
    $scope.templates = [
        {
        name: 'tasks',
        url: 'partials/_tasks.html'},
    {
        name: 'projects',
        url: 'partials/_projects.html'}
    ];
    $scope.template = $scope.templates[0];

    $scope.openProjects = function() {
        $scope.template = $scope.templates[1];
    };
    $scope.openTasks = function() {
        $scope.template = $scope.templates[0];
    };
});

_projects.html

<div ng-controller="ProjectsCtrl">
  <h2>My Projects</h2>
  ...            
</div>

_tasks.html

<div ng-controller="TasksCtrl">
  <h2>My Tasks</h2>
  ...            
</div>

My question is, what is the best solution for what I am trying to do without causing conflicting scopes?

1 Answer 1

4

So, I actually think your method is correct. I base this on the AngularJS documentation for controllers (the "Demo" section shows a simple nested controller hierarchy in action).

Further, this seems pretty similar to how the form directive works. It creates a scope for the form itself, evaluating $pristine, $dirty, $valid and $invalid for the overall form. Those values are only true if all its sub-scopes evaluate to true as well (in other words, a form is only $valid if all inputs return as $valid as well). This is done via a nested scope hierarchy, so if Angular does it in a fundamental way, then an application can do it similarly.

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

2 Comments

Although...if you're NOT tied to having these remain on the same page, you also could consider just routing each click to a different URL, since Angular makes it seem like the user is on the same page anyways.
The issue is I already have routing doing other dynamic loads of content. To do so here and keep track of state of the other parts seems like it would get real complicated quickly. If nested controllers isn't a sin per se then I will go with that and keep the WindowCtrl as simple as possible.

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.