1

This might be late to the game with Angular 2 being the new kid on the block, but I recently came across this in a corner of a project. I've not worked on many Angular apps of this scale (with regards to team members contributing), and I'd like to see why this code is implemented as follows:

app.js:

angular
    .module('myModule')
    .controller('AppCtrl', ['$scope','$rootScope', function($scope, $rootScope) {

        $scope.SideMenuCtrl = function ($scope) {
            $scope.staticMenu = _service.getMenuList($rootScope.acctId);
        };

    }]);

index.html:

<!DOCTYPE html>
<html ng-app="ngApp" ng-controller="AppCtrl">
<head></head>
<body>
<header></header>
<div id='wrapper' ng-hide="hideNav()">
    <div id='main-nav-bg'></div>
    <nav id='main-nav' class='main-nav-fixed'>
        <div class='navigation'>
            <ul class='nav nav-stacked' ng-controller="SideMenuCtrl">
            </ul>
        <div>
    <nav>
</div>

Question:

I'm trying to understand why / what the reasoning / benefit would be to assign nested controllers like this, and not having dedicated angular controllers? Isn't this breaking (assumed) convention / mixing different purposes?

Rohan Büchner
  • 5,333
  • 4
  • 62
  • 106

2 Answers2

1

In essence you are correct but some controllers have such limited responsibilities that it is the lesser of two evils. Either clunk up your folders with another controller file or you quickly write it at the only place it will be used.

In short the questions you should be asking is :

  1. Will this controller only be used here?
  2. Is it compact in size.

If both of these questions have yes as an answer, write it inline.

Arno_Geismar
  • 2,296
  • 1
  • 15
  • 29
  • ... this might be somewhat purist of me, but I don't see the benefit of just having a controller for just this one item? (If it was a directive or component, it would be different) But would it be a valid statement in saying if the controller only has this one property, why isn't this property just part of the parent in the first place? – Rohan Büchner Nov 15 '16 at 08:54
  • @RohanBüchner in this specific case I think it will be dificult since the controller is the top level controller . But indeed if you are not building a reusable component and it is this limited in size then by all means put it in the parent controller. – Arno_Geismar Nov 15 '16 at 08:59
1

The main reason for this is that it is easy to maintain small controllers like this. This is useful especially if your controller will be used for very small feature and you don't really need dedicated controllers for this.

Especially if the application is big, this helps to keep the tree organized.

stormec56
  • 162
  • 2
  • 16