Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload AngularJS Controller

I'm a newbie to angularjs.

My problem is that I have a User Controller for handling Login and Logout. I have also another controller to load a header menu for my site.

If the user logs in to the site my isAuthenticated variable is set to true. If the variable is set to true the header should be change but, so I think the controller must be reloaded to change the header view.

Here the code of my HeaderController:

myapp.controller('HeaderController', ['$scope', '$location', '$window', 'AuthenticationService',  
    function HeaderController($scope, $location, $window, AuthenticationService) {
        $scope.isAuthenticated = AuthenticationService.isAuthenticated;

        if (AuthenticationService.isAuthenticated) {
            $scope.user.vorname = $window.sessionStorage.user.vorname;
        }
    }
]);

Here's the code of my HeaderDirective:

myapp.directive('appHeader', function() {
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      if (attrs.isauthenticated == 'false') {
        scope.headerUrl = 'views/header/index.html';
      } else {
        scope.headerUrl = 'views/header/isAuthenticated.html';
      }
    },
    template: '<div ng-include="headerUrl"></div>'
  }
});

My index.html:

<div ng-controller="HeaderController">
  <app-header isauthenticated="{{isAuthenticated}}"></app-header>
</div>

How can I reload the controller if the user logs in to the page?

PS: Please excuse my poor pronunciation.

like image 892
Rico Berger Avatar asked Oct 02 '14 22:10

Rico Berger


People also ask

How to reload the controller in AngularJS?

Reload Page Using the reload() Method in AngularJS The route's controller includes services that are named in a case when the controller is constructed, and we may recall these exact services to refresh the information when a condition occurs.

How to reload page in AngularJS?

For the record, to force angular to re-render the current page, you can use: $route. reload();

How to reload page on button click in AngularJS?

function runPublicationBatch(){ $window. location. reload(); var invoice = new Array(); if (vm. validInvoiceList) { vm.

What is $timeout in AngularJS?

The '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.


1 Answers

Add this piece of code after the user is authenticated:

// To refresh the page
$timeout(function () {
    // 0 ms delay to reload the page.
    $route.reload();
}, 0);

Don't forget to include $timeout and $route in your controller.

myapp.controller('HeaderController', ['$scope', '$location', '$window', 'AuthenticationService', '$timeout', '$route',
function HeaderController($scope, $location, $window, AuthenticationService, $timeout, $route)
like image 166
mpatel Avatar answered Sep 29 '22 23:09

mpatel