Search code examples
angularjsarchitectureng-controller

"Direct nesting" of ng-controllers. Is this normal?


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?


Solution

  • 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.