How do I keep a child controller from inheriting the scope of the parent controller in AngularJS?

If I have a nested controller in AngularJS (one controller inherits from another), how do I get the child controller to access the scope of the parent controller? This was asked for me by an interview question.

+3


source to share


2 answers


Unable to allocate controller scope:

Next, new scopes are created and inherited prototypically: ng-repeat, ng-include, ng-switch, ng-view, ng-controller , scoped directive: true, with transclude directive: true. doc



To create an isolated scope, you must use a directive instead of a controller. Make sure you define the scope property in your directive declaration. doc

+2


source


When using an ng controller, you cannot isolate the scope, however you can isolate the methods on the controller, returning rather than the controller and not putting them in scope.

.controller('myCtrl', function() {
    return {
        doStuff: function() {
        }
    }
})

      



The child controller will not have access to the function doStuff

. The only way to use it is to usecontroller as

<div ng-controller="myCtrl as parentCtrl">
    <button ng-click="parentCtrl.doStuff()"/>
</div>

      

+2


source







All Articles