javascript - ng-if block 中的函数不起作用

标签 javascript angularjs

嗨,我尝试使用 Angular 和本地存储进行身份验证。我遇到了这个问题。

下面是我的 app.js 中的部分代码

app.run(function($window,$rootScope){

    $rootScope.isAuthed=function(){
        console.log("starting isAuthed...."+$window.localStorage.getItem("isAuthenticated"))
        return $window.localStorage.getItem("isAuthenticated")
    }
    $rootScope.whoIsCurrenUser=function(){
        return $window.localStorage.getItem("currentUser")
    }

    $rootScope.logout=function(){
        if(confirm("Are you sure to log out ?")){
            $window.localStorage.setItem("isAuthenticated", false);
            $window.localStorage.setItem("currentUser", "");
        }
    }
})

在我的 html 中,我尝试在 ng-if 中应用 isAuthed 函数,但它不起作用

 <ul class="nav navbar-nav navbar-right">
                    <li ng-if="!isAuthed()"><a ng-click="loginDialog()">Log In</a></li>
                    <li ng-if="isAuthed()"><a ng-click="logout()">Log Out</a></li>
  </ul>

我可以在控制台上看到 isAuthenticated 设置为 true enter image description here

但是我的页面上没有显示登录或注销..

enter image description here

我的问题如本文标题所示:为什么 ng-if block 中的函数不起作用?

最佳答案

一个简单的解决方案是将 isAuthed 函数的结果与字符串进行比较,结果为“true”。代码可以是:

$rootScope.isAuthed=function(){
    console.log("starting isAuthed...."+$window.localStorage.getItem("isAuthenticated"))
    return $window.localStorage.getItem("isAuthenticated") === "true";
}

关于javascript - ng-if block 中的函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461565/

相关文章:

javascript - 具有很少角色访问权限的 Angular JWT

javascript - 使用node.js async 和 require 获取多个url

javascript - 更改静态 HTML 表中 <td> 的颜色,这取决于没有 ng-Repeat 的 AngularJS 中后端数据是否为真

javascript - AngularJS 和 owl-carousel 环境中的数组串联

javascript - Jquery 附加来自 LaravelBalde 的内容

javascript - 在不同网站上完成操作后,使用 YouTube API 点赞视频

javascript - 如何使 Javascript/JQuery 对象方法可在整个 HTML 页面中访问

javascript - 如何在 jQuery 中高效处理 jQuery(window).scroll 函数?

javascript - 接受字符串的 Angular 指令

angularjs - 为什么我从ng-show =“!emptyArray”和ng-hide =“emptyArray”得到不同的结果?