gpt4 book ai didi

javascript - Angular -Js : not able to access array elements in different function call within same controller

转载 作者:行者123 更新时间:2023-12-02 15:39:17 24 4
gpt4 key购买 nike

我只需要在 register() 调用时将数据存储在 $scope.user 中,并尝试使用其数据元素登录。但没有成功。我使用了最简单的方法,我想,可能还有其他方法(如 localStorage、cookie 等)。我对 Angular 很陌生,不知道如何实现它们。请帮帮我...

Controller :

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>

如果有人能帮助我解决这个问题,我将非常感激。

最佳答案

您将用户数据推送到数组中,您的 $scope.user 是一个数组,而不是一个对象。试试这个:

$scope.user = {};  

$scope.register = function(userData){
$scope.user = userData;
alert($scope.user.username);
};

关于javascript - Angular -Js : not able to access array elements in different function call within same controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32695872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com