I find that sometimes it is better to use angularJS services to communicate between two component rather than using emit/broadcast techiques. I have create simple UserService:
(function(){
angular.module('userService')
.factory('UserService', userServiceFn);
userServiceFn.$inject = [];
function userServiceFn(){
var user = {
isLogged: false,
info: ''
};
return {
setUser: setUser,
getUser: getUser,
clearUser: clearUser
};
function setUser(info){
user.isLogged = true;
user.info = info;
};
function getUser(){
return user;
};
function clearUser(){
user.isLogged = false;
user.info = {};
};
}
})();
then I can inject this service where ever I need to no current login status var user = UserService.getUser(); and for example toggle login button <button ng-hide="user.isLogged">login</button>
Great thing about this technique is that when ever I use UserService.clearUser() login button will automatically be shown because getUser() passes a reference of user object and ng-hide binds to changes in this reference.
I created MarkerService that uses same techique but there is strange behavior. getCoords does not return reference of coords but value of coords.
(function(){
angular.module('app')
.factory('MarkerService', MarkerServiceFn);
MarkerServiceFn.$inject = [];
function MarkerServiceFn(){
var coords = [
56.936,
22.12
];
return {
setCoords: setCoords,
getCoords: getCoords
};
function setCoords(a){
console.log(coords);
coords = a;
console.log(coords);
}
function getCoords(){
return coords;
}
}
})();
Here is a working plunker. What confuses me is that both service are created in the same way but act differently. Have spent two days finding for reason of this behavior, even re-wrote code for both services couple of times but always get the same issue.