Manish
Manish

Reputation: 65

Share data between siblings Angularjs

I have nodes like this

             3
       ------------
       |          |
     -----     ------
     1   |     2    |

I want communication between 1 & 2

I found a method on stackoverflow which is like

two.js

$scope.$emit('messageTwo', someValue(s));

three.js

$scope.$on('messageTwo', function( event, data ){
  $scope.$broadcast( 'messageTwo', data );
});

one.js

$scope.$on('messageTwo', someValue(s));

This method works perfectly. I tried the below option and it works. Is the below code correct way too?

two.js

$scope.$emit('messageOne', someValue(s));

one.js

$scope.$parent.$on('messageOne', function( event, data ){
  console.log( data );
});

Upvotes: 3

Views: 484

Answers (2)

Pravin Erande
Pravin Erande

Reputation: 89

If you want to share data between sibling you could use either service or factory.

If its in between parent to child or child to parent you could go with $broadcast or $emit or simply make use of $rootscope.

Upvotes: 0

yscik
yscik

Reputation: 879

It does work, but you will need to unregister the listener manually when scope one is getting destroyed.

var messageListener = $scope.$parent.$on('messageOne', ...)
$scope.$on('$destroy', messageListener)

You can also just go the other way around and broadcast on the parent scope or even $rootScope.

two.js

$scope.$parent.$broadcast('messageOne', someValue(s));

one.js

$scope.$on('messageOne', function( event, data ){
  console.log( data );
});

If you need access to the $scope of one.js in event.targetScope though, $emit is way to go.

If you just want to share data, you could also use a shared service instance or simply a variable on the shared parent controller's scope.

Upvotes: 2

Related Questions