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?

Any help much appreciated.


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.

链接地址: http://www.djcxy.com/p/76956.html

上一篇: SBT项目发布两件神器的惯用​​方式是什么?

下一篇: 在另一个控制器中包含控制器