我是Angular JS的新手,并且想要从登录表单开始。我阅读了一些在线资料,并决定试一试。
下面是我的代码,当我点击“登录”时,没有任何反应,我不确定我的html脚本是否与控制器对话,或者我是否在控制器中编码错误。
<!DOCTYPE html>
<html data-ng-app="loginAuth">
<head>
<title>
</title>
</head>
<body>
<h2>Angular Authentication</h2>
<div data-ng-controller="loginController">
<label>Username</label>
<input type="text" name="username" data-ng-model="login.username"/>
<br/>
<label>Password</label>
<input type="password" name="password" data-ng-model="login.password"/>
<br/>
<input type="button" ng-submit="login.submit(login.username, login.password)" value="Login"/>
<br/><br/>
{{login.message}}
</div>
<script src="angular.min.js"></script>
<script>
'use strict';
angular.module('loginAuth')
.controller('loginController', function ($scope)
{
function login.submit(username, password)
{
if (username === 'admin' && password === 'test99')
{
.then(onSuccess);
}
else
{
.catch(onError);
}
}
function onSuccess()
{
login.message = 'Login Successful!';
}
function onError(reason)
{
login.message = reason.message;
}
});
</script>
</body>
</html>
有人可以帮帮我吗。
答案 0 :(得分:1)
你的app应该以适当的方式定义。
angular.module('loginAuth', [])
您还需要正确定义控制器方法
<强>控制器强>
angular.module('loginAuth')
.controller('loginController', function($scope) {
$scope.login = {};
$scope.login.submit = function(username, password) {
if (username === 'admin' && password === 'test99') {
//.then(onSuccess); //this is something wiered
} else {
//.catch(onError); //this is something wiered
}
}
function onSuccess() {
$scope.login.message = 'Login Successful!';
}
function onError(reason) {
$scope.login.message = reason.message;
}
});
答案 1 :(得分:0)
我对原始代码进行了更改以使其正常工作。希望这会帮助你学习一些Angular:)
<!DOCTYPE html>
<html data-ng-app="loginAuth">
<head>
<title>
</title>
</head>
<body>
<h2>Angular Authentication</h2>
<div data-ng-controller="loginController">
<label>Username</label>
<input type="text" name="username" data-ng-model="login.username"/>
<br/>
<label>Password</label>
<input type="password" name="password" data-ng-model="login.password"/>
<br/>
<input type="button" ng-click="login.submit(login.username, login.password)" value="Login"/>
<br/><br/>
{{login.message}}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script>
'use strict';
angular.module('loginAuth', [])
.controller('loginController', function ($scope) {
$scope.login = {};
$scope.login.submit = function(username, password)
{
if (username === 'admin' && password === 'test99')
{
onSuccess();
}
else
{
onError({message:'login failed'});
}
}
function onSuccess()
{
$scope.login.message = 'Login Successful!';
}
function onError(reason)
{
$scope.login.message = reason.message;
}
});
</script>
</body>
</html>