Reputation: 748
i have faced this question in an interview, i know how to share data between two controllers using service and also using root scope. Is there any way to do with in angular to pass data between two controllers without using service and root scope>
Any suggestions please.
Upvotes: 0
Views: 234
Reputation: 1298
The best practice states using a service, you could also use $rootScope
by assigning object literal $rootScope.sharedVar
. There's also a $broadcast
method, which is an observer pattern, works like pub/sub.
The least recommended way would be leveraging your $parent
scope and drilling down your element (depending where it's located in the DOM tree)
Upvotes: 1
Reputation: 329
AngularJs uses the Observer pattern which consists on sending and reading events.
There are many times when one part of the application changes, other parts needs to be updated. In AngularJS, if the $scope object updates, an event can be triggered to notify another component. The observer pattern incorporates just that - if an object is modified it broadcasts to dependent objects that a change has occurred.
In short:
$scope.$emit()
OR $scope.$broadcast()
depending on your position and what is your 'reader'
Then
$scope.$on()
Upvotes: 1