Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing re-evaluation of ng-if

Tags:

angularjs

I have a header on my application that contains the 'Sign In'/'Create Account' option. When the user logs in I need the aforementioned to swap for the 'Sign Out' option.

However when the user logs in the ui-view changes as expected but doesn't change the header, understandable because it isn't part of the ui-view. Here's my code so far:

<ul id="nav-account">
    <li>{{mainCtrl.isAuthenticated ? 'Welcome ' + user.firstname + '!'</li>
    <li ng-if="!isAuthenticated"><a ng-href="{{'HEADER_NAVTABS_SIGNIN'| externallinks}}">Sign In</a> or <a ng-href="{{'HEADER_NAVTABS_CREATE_ACCOUNT'| externallinks}}">Create Account</a></li>
    <li ng-if="isAuthenticated"><a ui-sref="logout">Sign Out</a><li>
</ul>

In my controller I'm setting the value of isAuthenticated by calling a service:

 $scope.isAuthenticated = memberService.isAuthenticated();

The only way that the header value will change is if I refresh the whole page - why is this? Shouldn't the ng-if re-evaluate the variable and update the view accordingly?

Does this mean that ng-if is only bound one way? So what can I do to make this work?

Thanks

Andrew

like image 620
Katana24 Avatar asked Jan 02 '15 11:01

Katana24


1 Answers

Your controller's code is called only on associated template's load time. This means that the variable won't be reaffected later.

However, databinding is valid everywhere including if ngIf. To use it and according to explained earlier, I suggest you two simple and clean solutions:

1. Bind the function (or the service) in your controller's scope:

Angular:

$scope.isAuthenticated = memberService.isAuthenticated;

Partial:

<li>{{isAuthenticated() ? 'Welcome ' + user.firstname + '!'}}</li>

Note the use of parenthesis: this will let angular evaluate isAuthenticated() in each digest loop.

-

2. Bind an authentication object in your scope that can be modified by the service:

Angular:

$scope.auth = memberService.authenticationData;

Partial:

<li>{{auth.isAuthenticated ? 'Welcome ' + user.firstname + '!'}}</li>

-

Moreover, like suggested by @Govan, you should prefer directives like ngShow rather than manual JS tests:

<li ng-show="auth.isAuthenticated">Welcome {{user.firstname}}!</li>
like image 78
ngasull Avatar answered Oct 17 '22 12:10

ngasull