我是棱角分明的新手,所以我需要帮助。
在html中,我写了以下内容
<div class="form-group">
<input type="email" name="Email" id="LoginEmail class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
在角度,我写下面的代码
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [
{name : "User1",
account : "user1@whatever.com",
city: "XYZ",
password: "Angular@2017"}
];
}]);
我需要将输入框的值与脚本的值进行比较,如果不正确则显示一条消息,那我该怎么办呢?
答案 0 :(得分:0)
在输入元素中,您会错过ng-model属性。它用于将值与范围变量绑定。
<input type="email" ... ng-model="email" ...>
<input type="password" ... ng-model="password" ...>
在你的控制器中你可以写
if($scope.email == $scope.userinfo[0].account && $scope.password == $scope.userinfo[0].password){
//Login ok
}else{
//Login failed
}
答案 1 :(得分:0)
假设上面某处有一个表单元素
将ng-submit
添加到其中
<form ng-submit="submit()">
将
ng-model
添加到表单元素。
我添加了state.email
和state.password
<div class="form-group">
<input ng-model="state.email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="state.password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
将绑定值与
中的值进行比较$scope.userinfo
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [{
name : "User1",
account : "user1@whatever.com",
city: "XYZ",
password: "Angular@2017"
}];
// when you submit the form, this function will be called
$scope.submit = function (e) {
e.preventDefault();
if ($scope.state.email !== $scope.userinfo[0].account || $scope.state.password !== $scope.userinfo[0].password) {
// did not match
} else {
// matched
}
}
}]);
答案 2 :(得分:0)
首先,您需要将模型分配给模板范围。为此目的使用ng-model
。然后,您需要一个表单来提交并触发一个函数来检查用户输入是否与所需的值匹配。
添加ng-model
并使用表单标记包装输入:
<form ng-submit="login()">
<div class="form-group">
<input ng-model="email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
<button type="submit">Login</button>
</form>
检查用户输入在Controller中是否有效:
$scope.login = function() {
const isUserValid = $scope.email === $scope.userinfo[0].account && $scope.password === $scope.userinfo[0].password;
if(isUserValid) {
alert("Logged In Successfully");
}else {
alert("Email or password incorrect. Try again.")
}
}