$ Scope value is not updated in another controller

I have a problem updating the value in my view. Let me show you my code with a little explanation of what is going on. I know that the code is a bit dirty since I tried a lot of code combinations right now.

I have this accCtrl controller

controllers.accCtrl = function($scope, sessionFactory){
    sessionFactory.isLoggedIn().then(function(data){
        console.log(data.logged_in);
        $scope.loggedIn = data.logged_in;
    });
    $scope.logOut = function(){
        sessionFactory.logOutUser().then(function(data){
            $scope.loggedIn = data.logged_in;
        });
    }
}

Logout console false, and this $ variable scope.loggedIncontrols my html, showing or hiding login, registration, my profile and exit buttons

<div ng-controller="accCtrl">
    {{loggedIn}}
        <ul>
        <li ng-hide="loggedIn">
            <a href="#/login">
                <b>Login</b>
            </a>
        </li>
        <li ng-hide="loggedIn">
            <a href="#/register" >
                <b>Register</b>
            </a>
        </li>
        <li ng-show="loggedIn" >
            <a href="#/my_profile">
                <b >My profile</b>
            </a>
        </li>
        <li ng-show="loggedIn"> 
            <a ng-click="logOut()">
                <b>Log out</b>
            </a>
        </li>
    </ul>
</div>

Now the user is trying to log in, so he presses the login button and the login form is displayed. This login function is written in loginCtrl

    controllers.loginCtrl = function($scope, $http, $location, $timeout, sessionFactory){
    $scope.loginUser = function () {
        $http({
            method: 'POST',
            url: $location.protocol() + '://' + $location.host() + '/server/api/users/login',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            data : $.param({
                username : $scope.username,
                password : $scope.password
            })
        }).success(function(data){
                sessionFactory.isLoggedIn().then(function(data){
                    $scope.loggedIn = data.logged_in;
                });
                window.location.href="/#/home";
        });
    };
}

, , , , $scope.loggedIn , console.log(data.logged_in) loginCtrl true

, , accCtrl. , , .

sessionFactory , , ,

app.factory('sessionFactory', ['$http', '$location', function($http, $location){
    var factory = {};

    factory.logOutUser = function(){
        return $http({
            method: 'GET',
            url: $location.protocol() + '://' + $location.host() + '/server/api/users/logout'
        }).then(function successCallback(response){
            return response.data;
        },function errorCallback(response) {
            console.log('error logging out: ' + response);
        });
    }
    factory.isLoggedIn = function(){
        return $http({
            method: 'GET',
            url: $location.protocol() + '://' + $location.host() + '/server/api/users/isLoggedIn'
        }).then(function successCallback(response){
            console.log(response.data);
            return response.data;
        },function errorCallback(response) {
            console.log('Checking login failed: ' + response);
        });
    }

    return factory;
}]);

my app.js

var app = angular.module('app', ['ngRoute', 'ngAnimate', 'ui.sortable', 'ngFileUpload'])
app.config(function($routeProvider){
    $routeProvider.
    when('/', {controller:'homeCtrl', templateUrl:'app/templates/home.html'}).
    when('/home', {controller:'homeCtrl', templateUrl:'app/templates/home.html'}).
    when('/contact', {controller:'contactCtrl', templateUrl:'app/templates/contact.html'}).
    when('/about_us', {controller:'aboutUsCtrl', templateUrl:'app/templates/aboutUs.html'}).
    when('/cookies', {controller:'cookiesCtrl', templateUrl:'app/templates/cookies.html'}).
    when('/faqs', {controller:'faqsCtrl', templateUrl:'app/templates/faqs.html'}).
    when('/register', {controller:'registerCtrl', templateUrl:'app/templates/register.html'}).
    when('/login', {controller:'loginCtrl', templateUrl:'app/templates/login.html'}).
    when('/my_profile', {controller:'myProfileCtrl', templateUrl:'app/templates/myProfile.html'}).
    when('/trade/:param1', {controller:'tradeCtrl', templateUrl:'app/templates/trade.html'}).
    when('/user/:param1', {controller:'userCtrl', templateUrl:'app/templates/user.html'}).
    when('/swap/:param1', {controller:'subCategoriesCtrl', templateUrl:'app/templates/subCategories.html'}).
    when('/swap/:param1/:param2', {controller:'products', templateUrl:'app/templates/products.html'}).
    when('/swap/:param1/:param2/:param3', {controller:'product', templateUrl:'app/templates/product.html'}).
    otherwise({ redirectTo: '/home'});
  });

, , - , , , .

Work as expected

, , loginCtrl, accCtrl

enter image description here

f5 accCtrl.

enter image description here

loginCtrl, $scope.loggedIn accCtrl

, ,

+4
2

- , angularjs , . - accCtrl, , . ctrl+f5 , . $window.location.reload() . $window.location.reload(), , . ngRoute, , , , $window.location.reload();

.success(function(data){
                sessionFactory.isLoggedIn().then(function(data){
                    $scope.loggedIn = data.logged_in;
                });
                window.location.reload(); //the only workaround i could find with ngroute as for now.
                window.location.href="/#/home";
        });

ui.Router i.e., $stateProvider .

.state('home', {
    url: '/home',
    templateUrl: 'templates/home.html',
    controller: 'accCtrl',
    reload: true //will reload controller when state is being access
});

$state.transitionTo($state.current, {}, { reload: true, inherit: true, notify: true });

$state.go('.', null, { reload: true });

, , , .

+5

, 2 $scope.loggedIn.

1) , $scope.loggedIn; , promises , , .

sessionFactory.isLoggedIn().then(function(data){
    console.log(data);                     (2)
    $scope.loggedIn = data.logged_in;
    console.log($scope.loggedIn);          (3)
});
console.log($scope.loggedIn);              (1) <-- executes first before promise resolves
window.location.href="/#/home";

, , false, . , , . promises .

2) angular ajax- angular , angular. angular $rootScope.$apply() $scope. $apply(). . , :

$http({
    method: 'POST',
    url: $location.protocol() + '://' + $location.host() + '/server/api/users/login',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data : $.param({
        username : $scope.username,
        password : $scope.password
    })
}).success(function(data){
    ...
    $rootScope.$apply();
});
+2

Source: https://habr.com/ru/post/1629674/


All Articles