Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-include controller inside another controller

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?

like image 638
Darwin Tech Avatar asked Jan 16 '14 00:01

Darwin Tech


1 Answers

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.

like image 77
user3043124 Avatar answered Sep 29 '22 09:09

user3043124