I need to call method for initialization user setting values (which are set to rootscope) from second cotroller in method of the first controller.
After the values are succesfully set to rootscope return premise and continue in executing of the second method of the first controller.
I tried it with emit and broadcast examples, but without luck.
Could somebody please give me a advice how to do it correctly?
I am on Angular 1.2 and Ionic 1, beta 13
Many thanks for any help.
Template:
<ion-view title="{{ 'DAYS_RESULTS' | translate }}" >
<ion-content ng-controller="DailyStatsCtrl" ng-init="setData()">
Code:
// First cotroller call setData in ng-init
angular.module('starter')
// Controller definition
.controller('DailyStatsCtrl', function($scope, $rootScope, $ionicSlideBoxDelegate, $timeout , $ionicLoading , $q, $translate, DialsComputeService, cordova, LocalStorService, $ionicPopup, $state, $ionicNavBarDelegate, testService, $ionicPlatform) {
$scope.setData = function() {
$ionicPlatform.ready(function() {
$timeout(function() {
$scope.$emit("onSomething", "");
alert("TEST");
}, 1000);
});
};
In the second controller:
angular.module('starter')
// Controller definition
.controller('SettingsCtrl', function($scope, $rootScope, $ionicLoading, $ionicPlatform, LocalStorService, $timeout, $translate, $ionicPopup, $state, $ionicNavBarDelegate) {
$scope.getUserSettigns = function() {
alert("received");
$scope.test = 'event received';
}
$scope.$on('onSomething', function(e) {
$scope.getUserSettigns();
});
I have literally just done some event emitting. It is a pain but here is down low:
This will emit events down the children scopes
Angular Doc Definition:
This will emit events up to the parent scopes
Angular Doc Definition:
Me and my collegue believe that this is the best method. But also I believe this is the most reliable:
In the controller / service that is dispatching the event inject the
$rootScope
and use$broadcast
On the controller / service that is receiving the event, inject the
$scope
and use$on
This way the
$rootScope
will always be$broadcast
ing down the scope hierarchy because - as the name suggests - it is the root scope. So now you don't have to worry about whether to use$emit
or$broadcast
because using the$scope
means it will always be a child of$rootScope
.So in your case it's easy. The first controller should have
$rootScope
injected and use$broadcast
. The second controller should have$scope
and use$on
, and look like this:Here is a working plunker: http://plnkr.co/edit/PrD3vB80lFSt0a9WQLJ9?p=preview