adict
adict

Reputation: 41

How to nest angularjs controllers and directives?

If I nest my controllers like this:

<body ng-app="app" ng-controller="ctrl">

    <div ng-controller="app-get">
        <app-get></app-get>
    </div>
    <div ng-controller="app-post">
        <app-post"></app-post>
    </div>
    <div ng-controller="app-update">
        <app-update></app-update>
    </div>

</body>

Why is application only capable of interpreting only the first controller (app-get), while other two are unable to load correctly?

Upvotes: 0

Views: 113

Answers (1)

nrg
nrg

Reputation: 518

You have a typo in your markup, but I am not sure if it's the issue, because you did not share any other code:

<div ng-controller="app-post">
    <app-post"></app-post>
              \
               what's that double quote doing here?
</div>

Anyway, here is a simple snippet I wrote to demonstrate how one can achieve the layout you're trying to implement:

angular.module('app', [])
  .controller('AppController', AppController)
  .controller('AppGetController', AppGetController)
  .controller('AppPostController', AppPostController)
  .controller('AppUpdateController', AppUpdateController)
  .directive('appGet', appGetDirective)
  .directive('appPost', appPostDirective)
  .directive('appUpdate', appUpdateDirective);

function AppController() {
  this.hello = 'Hello from AppController!';
}

function AppGetController() {
  this.hello = 'Hello from AppGetController!';
}

function AppPostController() {
  this.hello = 'Hello from AppPostController!';
}

function AppUpdateController() {
  this.hello = 'Hello from AppUpdateController!';
}

function appGetDirective() {
  return {
    template: '<h3>Hello from appGet directive!</h3>'
  };
}

function appPostDirective() {
  return {
    template: '<h3>Hello from appPost directive!</h3>'
  };
}

function appUpdateDirective() {
  return {
    template: '<h3>Hello from appUpdate directive!</h3>'
  };
}
html, body { margin: 0; padding: 0; }
body { background: #f3d250; padding: 10px; }
h1, h2, h3 { margin: 0; padding: 10px; }
h3 { background: #5da2d5; }
div { background: #f78888; margin: 10px; padding: 0 10px 10px; }
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
  </head>
  <body ng-app="app" ng-controller="AppController as app">
    <h1>{{app.hello}}</h1>

    <div ng-controller="AppGetController as appGet">
      <h2>{{appGet.hello}}</h2>
      <app-get></app-get>
    </div>
    
    <div ng-controller="AppPostController as appPost">
      <h2>{{appPost.hello}}</h2>
      <app-post></app-post>
    </div>
    
    <div ng-controller="AppUpdateController as appUpdate">
      <h2>{{appUpdate.hello}}</h2>
      <app-update></app-update>
    </div>
  </body>
</html>

Upvotes: 1

Related Questions