0

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?

Amogh Talpallikar
  • 12,084
  • 13
  • 79
  • 135

3 Answers3

2

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

Chandermani
  • 42,589
  • 12
  • 85
  • 88
1

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

$scope.$parent.sharedProperty = someValue;
karaxuna
  • 26,752
  • 13
  • 82
  • 117
1

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.

Community
  • 1
  • 1
pedromarce
  • 5,651
  • 2
  • 27
  • 27
  • I was thinking the same but I want to use these properties in ng-show, ng-disable directives in HTML I need something in the scope anyways. – Amogh Talpallikar Feb 18 '14 at 10:43
  • Yes, your service will be in the scope, so you will be able to access those properties, just prefix them with the service you have injected. – pedromarce Feb 18 '14 at 10:47
  • Something like this ? $scope.injectedService = injectedService; $scope.injectedService.property = 5 – Amogh Talpallikar Feb 18 '14 at 10:51
  • No need, just add the service as a dependency when defining the controller (that will injected) and then just use $scope.service.property instead of $scope.property. The approved answer for the SO question I have linked is a very fine example. – pedromarce Feb 18 '14 at 10:56