简体   繁体   中英

Angular ng-show not working properly

I have the below HTML and then the JS below that with my service and controller:

    <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav navbar-right" ng-show="is_authenticated">
            <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Account <b class="caret"></b></a>
                <ul class="dropdown-menu">
                    <li><a href="#">Account</a></li>
                </ul>
            </li>
        </ul>
        <ul class="nav navbar-nav navbar-right" ng-hide="is_authenticated">
            <li ng-class="{ active: register }"><a href="#/register">Sign Up</a></li>
            <li ng-class="{ active: login }"><a href="#/login">Sign In</a></li>
        </ul>
    </div>

The ng-hide works properly, however, the ng-show does not.

    Auth.is_authenticated()
        .success(function(data) {
            $scope.is_authenticated = data.authenticated;
        });

Service:

    return {
        is_authenticated: function() {
            return $http.get('/api/users/is_authenticated');
        },

When I go to the API endpoint in the URL it returns `{"authenticated": true}

What is this happening?

Edit:

When I view the source in the developer tools it seems like for some reason the HTML with <ul > for ng-show is not even there.

Should this be true?

Change is_authenticated function like :

Auth.is_authenticated()
        .success(function(data) {
            if(data.authenticated === 'true')
            {
              $scope.is_authenticated = true;
            }
            else
            {
              $scope.is_authenticated = false; 
            }

        });

You can simply change the value to a boolean and work accordingly. So you controller code will look like this:

 Auth.is_authenticated()
    .success(function(data) {
        $scope.is_authenticated = (data.authenticated. toLowerCase() === "true");
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM