angularjs parent child controller communication
An angular app App having a service myService, which holding an object data that is used by two Controllers, parentCtrl and childCtrl.
Here parentCtrl is parent of childCtrl, childCtrl inherits scope of parentCtrl.If we reference data within parentCtrl like
$scope.data = myService.getData()
which also makes it accessible from childCtrl.
Here data defined in the closure of myService, hence $scope.data is just a reference to data.
Now, If we altered data's properties within the child controller and everyone, myService, parentCrl and childCtrl will be aware of these changes.
If we want to overwrite the entire data object we need to invoke myServices method setData. If you invoke this method in parentCtrl, myService, parentCrl and childCtrl will be aware of these changes. If you did the same within childCtrl it is not notified to all.
To solve this Issue we can use $broadcast and $on
More information refer http://frontendx.blogspot.in/2016/02/angularjs-provides-on-emit-and.html
This is the setData function of myService
function setData(newData) {
data = newData;
}
Update this function as below reffered
function setData(newData) {
data = newData;
$rootScope.$broadcast('dataHasChanged', {data : data});
}
Now in parentCtrl
$scope.$on('dataHasChanged', function(evt, args) {
$scope.data = args.data;
});
Here both myService and parentCtrl is notified when ever setData function is called.
This scenario helps to notify the modification to all when modification done outside of these three items(myService,parentCtrl,childCtrl).
No comments:
Post a Comment