我只需要在$scope.user
register()
调用中存储数据,并尝试使用其数据元素登录..但不成功。我用最简单的方法,我想,可能还有其他方法(比如localStorage,cookies等)我是角色的新手,不知道如何实现它们。请帮帮我...
控制器:
var app = angular.module("app",[]);
app.controller("ctr",function($scope){
$scope.user = [{
fname:"",
lname: "",
username: "",
password: ""
}];
$scope.register = function(userData){
$scope.user.push(userData);
alert($scope.user.username); *//show undefined*
};
$scope.login = function(loginData){
if(loginData.username == $scope.user.username) {
alert("Login successfully!!");
}
else alert("Wrong user!");
};
});
查看:
<body ng-app="app">
<div ng-controller="ctr">
<table >
<tr>
<td><label>Username : </label></td>
<td><input type="text" ng-model="loginData.username" placeholder="Name" /></td>
</tr>
<tr>
<td><label>Password : </label></td>
<td><input type="password" ng-model="loginData.password" placeholder="Password" /></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Login" ng-click="login(loginData)" class="save"/>
</td>
</tr>
</table>
<table >
<tr>
<td><label>First Name : </label></td>
<td><input type="text" ng-model="userData.fname" placeholder="First Name" /></td>
</tr>
<tr>
<td><label>Last Name : </label></td>
<td><input type="text" ng-model="userData.lname" placeholder="Last Name" /></td>
</tr>
<tr>
<td><label>Username : </label></td>
<td><input type="text" ng-model="userData.username" placeholder="Name" /></td>
</tr>
<tr>
<td><label>Password : </label></td>
<td><input type="password" ng-model="userData.password" placeholder="Password" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Register" ng-click="register(userData)" class="save"/></td>
</tr>
</table>
</div>
</body>
如果有人可以帮我解决这个问题,我真的很感激。
答案 0 :(得分:2)
您将userdata推送到数组,$scope.user
是一个数组,而不是一个对象。试试这个:
$scope.user = {};
$scope.register = function(userData){
$scope.user = userData;
alert($scope.user.username);
};
答案 1 :(得分:0)
由于变量$scope.user
是一个数组,你应该使用这样的东西:
alert($scope.user[0].username)
答案 2 :(得分:0)
您的if语句为false:
if(loginData.username == $scope.user.username) {
您的$scope.user
是一个数组,您应首先搜索具有此用户名的对象,然后才能比较密码。
$scope.login = function(loginData){
//Filter your user array and find the user with given username
var user = $filter('filter')($scope.user, function (u) {return u.username === loginData.username;})[0];
//Compare login data
if (user == null) {
alert("User not found");
} else {
if(user.password == loginData.password) {
alert("User logged in");
} else {
alert("Wrong Password");
}
}
};
我没有可能测试我的答案,请给我一个反馈。