I want to know how to correctly use the $emit
method correctly so that inside my error callback I can fire a modal.
I have the following factory:
angular.module('BBPlnkr').factory("Session", [
'$http', '$q', '$rootScope', function($http, $q, $rootScope) {
var service;
service = {
requestCurrentUser: function() {
if (service.isAuthenticated()) {
return $q.when(service.currentUser);
} else {
}
return $http.get('current_user').then(function(resp) {
console.log(resp.data);
service.currentUser = resp.data;
return service.currentUser;
}, function(resp) {
if (resp.status === 401) {
$rootScope.$emit("loginRequired", "err");
console.log('You are not authetnicated');
}
});
},
currentUser: null,
isAuthenticated: function() {
return !!service.currentUser;
}
};
return service;
}
]);
What this factory simply does is just checks if the user is the current_user and if not it returns a 401. What I'd like to do is inside that error callback is fire a modal when this error callback is called. Now I was found out I could use the $emit
method but am not sure if I am using it correctly. Inside the error callback I want to dispatch the event up through the scope chain. Which is what $emit
does right. But I am not entirely sure if I set this up correctly. So in doing this. I have my controller like so:
myApp.controller('MainController', ['$scope', '$rootScope', '$modal', '$location', '$route', function($scope, $rootScope, $modal, $location, $route) {
$rootScope.$on('loginRequired', function(event, second_param){
/* Do the modal stuff here??*/
});
}
]);
I am aware I am not actually doing anything to fire trigger a modal ($modal.open). BUT I wanted to know if I heading in the right direction. If not, some advice would be helpful. I have looked online for documentation around $emit
, $broadcast
. I know the difference between the two. Once dispatches events up the scope chain and one dispatches events down the $scope chain.