I am pretty new to the AngularUI Router and would like the use it for the following scenario:
The layout common to all pages includes a top navbar c
You should use:
$on and $emit
The emit controller, that sends the data.
angular.module('MyApp').controller('MyController', ['$scope', '$rootScope', function ($scope, $rootScope){
$rootScope.$emit('SomeEvent', data);
}]);
An example of how to implement $rootScope a safe way so it destroys and fixes stuff after use:
angular
.module('MyApp')
.config(['$provide', function($provide){
$provide.decorator('$rootScope', ['$delegate', function($delegate){
Object.defineProperty($delegate.constructor.prototype, '$onRootScope', {
value: function(name, listener){
var unsubscribe = $delegate.$on(name, listener);
this.$on('$destroy', unsubscribe);
},
enumerable: false
});
return $delegate;
}]);
}]);
And the controller with the data that should be treated.
angular.module('MyApp')
.controller('MySecondController', ['$scope', function MyController($scope) {
$scope.$onRootScope('SomeEvent', function(event, data){
console.log(data);
});
}
]);
You could pass in $rootScope instead of using the $scopes method $onRootScope that we defined in the config. However, this is not a recommended way of using $emit and $onRootScope.
Instead of using $emit, you could always use $broadcast. This would however give you very huge performance issues as your app grows. Since it bubbles the data through all controllers.
If your controllers are parents and child to each other, they don't have to use the $rootScope.
Here is and example of the difference between $emit and $broadcast: jsFiddle
And their is really performance differences:
