0

You are probably wondering what I mean by brothers components, well it's simply 2 different components that have the same parent component.

I am using angular.js 5.11

Let's say I have a parent component with a child1 component and a child2 component. I have a variable vm.active in my child1 component and I wish to use it (in an ng-if if you're wondering) in my child2 view.

Any ideas ? Was thinking of doing two way binding in both 3 components ? What do you all think ? Or maybe considering they are from the same state, probably as a stateParams ? Please let me know if you have any questions

Max
  • 1,103
  • 1
  • 10
  • 20
  • you mean angular 5 .11 you mean> – Obed Amoasi Feb 16 '18 at 14:16
  • simply treat components as controllers, then the solution would require a service to [share the common variables and methods](https://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers) – Aleksey Solovey Feb 16 '18 at 14:17

3 Answers3

1

This is the perfect scenario to create a service. Remember controllers have unique instances, but a service passes a common instance around.

https://www.w3schools.com/angular/angular_services.asp

QPSK
  • 17
  • 4
1

Do not use two-way data binding in this case because you can accomplish the same in a more efficient way. Two way binding setup requires framework overhead.

One approach:

Setup one way binding of the variable (say x) in the Parent component to both of the children.

When child1 makes an update to the variable, pass in an observable reference that the parent can receive. The parent can set the value of x accordingly. Now both the children can see the update.

Here's another:

Use a singleton service. Save the variable in a related service. Use the getters and setter methods to retrieve and update the values.

user6123723
  • 10,546
  • 18
  • 67
  • 109
0

Well ended up using $scope.$parent.$broadcast in first component and $scope.$on on the second component if anyone is wondering :)

Max
  • 1,103
  • 1
  • 10
  • 20