Answer the question
In order to leave comments, you need to log in
How to listen in a directive for changes in a service (Angular js)?
There is a service that is responsible for authorization:
function AuthService($http, ipCookie, $location){
return {
auth: auth,
isAuth: isAuth,
logout: logout
}
function auth(credentials, callback){
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
$http({
method: 'post',
url: '/rest/?route=user/login',
data: {'name': credentials.login, 'password': credentials.password}
}).success(Success);
function Success(data){
if(angular.isObject(data)){
ipCookie('login',data);
}
callback(ipCookie('login'));
}
}
function isAuth(){
var trigg = (ipCookie('login') === undefined) ? false : ipCookie('login');
return trigg;
}
function logout(){
$http({
method: "post",
url: '/rest/?route=user/logout'
}).success(Success);
function Success(data){
if(data == 0){
ipCookie.remove('login');
$location.path('login');
}
}
}
}
function navbarDirective(auth){
var elements = '<div class="navbar navbar-default" role="navigation" ng-show="menuShow">'+
'</div>';
return {
restrict: 'EA',
template: elements,
link: function(scope, element, attrs){
scope.$watch(function(scope){
if(auth.isAuth()) {
scope.menuShow = true;
scope.credentials = auth.isAuth();
}else{
scope.menuShow = false;
}
});
scope.logout = function(){
auth.logout();
}
}
}
}
Answer the question
In order to leave comments, you need to log in
For this it is better to use events. They will work instantly, they are not tied to $digest cycles, etc. Sculpting for this good bindings is unreasonably large overhead. In general, if we are talking about notification of a state change globally, then it is better to simply emit an event in $rootScope that will propagate down to all children.
ps why don't you use promises? instead of
myService.auth(data, function () {
alert('success');
});
myService.auth(data).then(function () {
});
myService.auth().then(function (userId) {
return user.get(userId);
}).then(function (user) {
// тут можно чего с пользователем поделать
return user.friends;
}).then(function (friends) {
if( !friends.length) {
return $q.reject('У вас 0 друзей :(');
}
return $q.all(friends.map(function (user) {
profile.get(user.id);
});
}).then(function (friendsProfiles) {
$scope.friends = friendsProfiles;
}, function (error) {
alert(error);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question