当我开始学习angulerjs时,我正面临着小问题。同时开发angulerjs应用程序。
我最近设置了登录过程,现在我被困在前端显示器上。 如果用户已登录,我想显示特定内容。 例如:
<!--show this if cookies is set to true -->
<li><a href="#/logout"><span class="icon mail"></span>Logout</a></li>
<!-- show this if cookies is undefined -->
<li><a href="#/login"><span class="icon mail"></span>Login</a></li>
我知道我必须使用ng-if。 如果登录值存储在cookie中,如何检查ng-if的条件?
控制器
app.controller('AngularLoginController', ['$scope', '$http','$cookies',
function($scope, $http, $cookies) {
$scope.loginForm = function() {
$http.post("login.php", {
'email' :$scope.inputData.email,
'password':$scope.inputData.password
}).success(function(data) {
console.log(data);
if ( data == 'correct') {
var loggedIn = $cookies.get('loggedIn');
// Setting a cookie
$cookies.put('loggedIn', true);
//window.location.href = 'welcome_dashboard.php';
}
else {
$scope.errorMsg = "Invalid Email and Password";
}
})
}
}]);
答案 0 :(得分:0)
在控制器中创建一个函数,使用简单的javascript
获取cookiefunction getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
检查Cookie是否存在
$scope.hasCookie=function(){
var ck=getCookie("your cookie name");
if(ck && ck !="")
return true;
return false;
}
<强> HTML 强>
<!--show this if cookies is set to true -->
<li ng-if="hasCookie()"><a href="#/logout"><span class="icon mail"></span>Logout</a></li>
<!-- show this if cookies is undefined -->
<li ng-if="!hasCookie()"><a href="#/login"><span class="icon mail"></span>Login</a></li>