parag baheti
parag baheti

Reputation: 31

How do I keep a child controller from inheriting a parent controller's scope in AngularJS?

If I have a nested controller in AngularJS (one controller inherits from another), how do I keep the child controller from having access to the parent controller's scope? This was asked as an interview question to me.

Upvotes: 3

Views: 244

Answers (2)

Enzey
Enzey

Reputation: 5254

With just using ng-controller you cannot isolate the scope, however you can isolate the methods on the controller by returning than on the controller and not placing them on the scope.

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

A child controller would not have access to the doStuff function. The only way to use it would be using the controller as

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

Upvotes: 2

Martin Schulz
Martin Schulz

Reputation: 592

There's no way to isolate controller's scope:

The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-view, ng-controller, directive with scope: true, directive with transclude: true. doc

To create an isolated scope, you should use directive instead of controller. Be sure that you defined a scope property in your directive declaration. doc

Upvotes: 2

Related Questions