嗨,我尝试使用 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
但是我的页面上没有显示登录或注销..
我的问题如本文标题所示:为什么 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/