Is it a problem to insert another controller into Angularjs?

Asked

Viewed 325 times

0

I have the following question: I am building a page, where I have a controller called PageController, responsible for rendering the menu and page title.

However, within the div where I use ng-controller="PageController", need to define where the page will be rendered - I am using the 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:

  • This departs from the standards recommended by Angularjs?

  • This may cause some problem?

  • What is the problem with the question? because the negative? could indicate so I can improve the details?

1 answer

4

This is no exception to the Angularjs standards, 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: https://docs.angularjs.org/guide/controller#Scope-inheritance-example

To this is given the name of Scope Inheritance or Heritage of Scope.

As for the problems, the most apparent that I see is the conflict of similarity between variables, functions, etc. But the Angular makes the reference to be made 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>
<div ng-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 regarding the use of separate controller together:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.