Is it a bad practice to have two Angular controllers that shares same DOM elements?

Imagine I have something like this:

<html ng-app="myApp">
    ...
    <body ng-controller="GlobalController">
        <div id="one">...</div>
        ...
        <div ng-controller="SpecificController" id="subPart">
            <div id="two">...</div>
            ...
        </div>
        ...
    </body>
</html>

As you can see, the controller GlobalController manages the whole body, while SpecificController only controls the subPart.

In that case, div#one can access to the GlobalController, but div#two is linked to GlobalController and SpecificController.

My question is to know if it's a bad practice to do that, because I imagine that having 2 controllers for the same DOM elements (such as div#two) can lead to conflicts...

Also, if it's not a bad practice, what should I take care in such situation? For example, I imagine that I have to be carefull to avoid having same properties in both controllers, right?

Thanks.

ps: I'm not sure if this question has been asked. I see several times the question "can I have the same controllers twice in the same page", but that's not my question.

Answers


There's nothing wrong with this in my opinion, you are just showing that there is an "inheritance" chain between your Controllers and it allows for more granular control over certain aspects of the DOM which may have nothing to do with the page as a whole.

You are correct about sharing properties, as the child controller will inherit its properties for the parent Controller:

function ParentCtrl($scope) {
    $scope.test = "One";
}

function ChildCtrl($scope) {
    console.log($scope.test); // Logs "One";
    $scope.test = "Two"; // We've re-defined the variable as "Two"
}

However, I would try to make it blindingly obvious in the code that SpecificController does indeed inherit from GlobalController in order to avoid collisions of data properties.


I have often found that if you try to keep everything in a single controller, especially for large pages, then the size of your controllers can become unmanageable, so its actually my preference to use parent - child controller inheritance. Just keep in mind that when referring to parent properties from child DOM elements, you need to be cautious of you parent property naming strategy or use $parent.parentproperty in the child DOM when you need to refer.


Need Your Help

history.back is breaking bind('scroll')

javascript jquery scroll browser-history

On the document ready of my page I bind the scroll event like this:

Disable Save button in WPF if validation fails

wpf validation save

I've adopted what appears to be the standard way of validating textboxes in WPF using the IDataErrorInfo interface and styles as shown below. However, how can I disable the Save button when the page