I am creating a SPA using AngularJS which has ng-view and a header as directive. In the view I have a button to authenticate using a service. Once a user is authenticated, I set a variable to TRUE in AuthenticationController. I use that variable in both ng-view and in directive. But only view part alone is refreshed, directive shows only the old value of the variable.
index.html
<body>
<app-header></app-header>
<div ng-view>
</div>
<script src="Scripts/libs/angular.js" type="text/javascript"></script>
<script src="Scripts/libs/angular-loader.js" type="text/javascript"></script>
<script src="Scripts/libs/angular-route.js" type="text/javascript"></script>
<script type="text/javascript">
var app = angular.module('myApp', ['ngRoute']);
app.directive('appHeader', function () {
return {
'restrict': 'E',
'templateUrl': 'Views/components/header.html'
};
});
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'Views/home.html'
})
.when('/', {
templateUrl: 'Views/landing.html',
});
}]);
</script>
<script src="Scripts/app/AuthenticationService.js" type="text/javascript"></script>
<script src="Scripts/app/HeaderController.js" type="text/javascript"></script>
<script src="Scripts/app/AuthenticationController.js" type="text/javascript"></script>
</body>
landing.html
<div ng-controller="AuthenticationController as authCtrl">
<input type="button" ng-click="doLogin()" value="Login"/>
{{isLoggedIn}}
</div>
header.html
<div ng-controller="AuthenticationController as authCtrl">
header {{isLoggedIn}}
</div>
AuthenticationController.js
app.controller('AuthenticationController', function ($scope, AuthenticationService) {
var authService = AuthenticationService;
$scope.isLoggedIn = false;
$scope.doLogin = function doLogin() {
$scope.isLoggedIn = authService.doLogin();
console.log($scope.isLoggedIn);
};
});
AuthenticationService.js
app.factory('AuthenticationService', function () {
return {
'isLoggedIn': false,
'doLogin': function doLogin() {
isLoggedIn = true;
return true;
},
}
});
I tried $scope.$apply()
, $scope.$digest()
but I used to get 'Digest is already inprogress' error. Can someone really spot out what is wrong in code or do I need to change the approach?
Thanks in advance!