Is there any problem in inserting a controller from another in angularjs?

0

I have the following question: I'm setting up a page, where I have a controller called PageController , responsible for rendering the menu and title of the page.

However, within div where I use ng-controller="PageController" , I need to set where the page will be rendered - I'm using angular-route . So, theoretically, I would have one controller inside the other.

So, I have something similar to this structure:

  <div ng-controller='PageController'>
    <h1 ng-bind="title"></h1>
    <ul>
        <li ng-repeat="url in urls"></li>
    </ul>
    <!-- aqui o angular vai executar outro controller, por causa do $routeProvider -->
    <div ng-view></div>
</div>

My question is:

  • Does this flush with the standards recommended by AngularJS?

  • Can this be a problem?

asked by anonymous 06.08.2016 / 18:19

1 answer

4

This does not escape anything to the standards of Angularjs, in the Controllers documentation itself there is an example with this very clear:

<div class="spicy">
  <div ng-controller="MainController">
    <p>Good {{timeOfDay}}, {{name}}!</p>

    <div ng-controller="ChildController">
      <p>Good {{timeOfDay}}, {{name}}!</p>

      <div ng-controller="GrandChildController">
        <p>Good {{timeOfDay}}, {{name}}!</p>
      </div>
    </div>
  </div>
</div>

Source: link

This is called Scope Inheritance or Scope Inheritance .

As for problems, the most apparent I see is the conflict of similarity between variables, functions, etc. More Angular causes the reference to be made to the nearest hierarchy. For example:

var app = angular.module("inheritanceExample", []);

app.controller("first", function($scope) {
  $scope.name = "João von Haller";
})
app.controller("second", function($scope) {
  $scope.name = "Maria Mangeth";
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="inheritanceExample" ng-controller="first">
  First Controller:
  <br> {{name}}
  <br>
  <hr>
  <div ng-controller="second">
    Second Controller:
    <br> {{name}}
  </div>
</div>

Here are some references to using separate controllers together:

06.08.2016 / 23:57