Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

How to modify controller property in parent scope from a child scope?

I have a parent controller that manages the partial in ng-view. It has 5 tabs, each tab has a form. Each form has it's own controller.

I am maintaing a variable in the parent scope. I want to modify it in one of the child controller's scope so that other controller's also view the change.

How is it possible ? Will a statement like $scope.sharedProperty = 5

make the one in parent as 5, or create a new one with that value in child scope?

Upvotes: 0

Views: 344

Answers (3)

pedromarce
pedromarce

Reputation: 5669

I would recommend to use as service to share properties, this way you avoid creating dependencies, just think if you need to reuse your view but not as a direct child but as a nested child, using a service angular would manage that for you without worries.

Check this answer for instance.

Upvotes: 1

karaxuna
karaxuna

Reputation: 26930

Agree with @Chandermani about services. But you can also modify parent scope like this:

$scope.$parent.sharedProperty = someValue;

Upvotes: 1

Chandermani
Chandermani

Reputation: 42669

Depends upon where you do it and type. If you are using string, int, bool etc and make changes in the child controller, no other controller including the parent would see them, as this would define an new property on the child controller.

If you create a object, such as $scope.sharedObject on the parent controller, then you can manipulate it anywhere in the child such as

$scope.sharedObject.prop1="newvalue";

and all others would see the change and watch over it using $scope.$watch.

Better way to share data between controllers is to use a service.

Also read on prototypal inheritance of $scope here https://github.com/angular/angular.js/wiki/Understanding-Scopes

Upvotes: 2

Related Questions