我是Angular JS的新手。这是我的第一个基本步骤。我创建了简单的登录页面以访问。我面临的问题是,当我单击login()
按钮时, form()没有提交,并且显示出无效的用户名和密码。我刚刚在其他一些博客中搜索。但是我不正确地理解。
下面有我的代码:
html:
<div class="package" ng-controller="credientials">
<form ng-submit="loginform()" class="ng-scope ng-pristine ng-valid">
<label form="emailinput">Email</label>
<input type="text" class="form-control ng-pristine ng-valid" ng-model="username">
<label form="pwdinput">Password</label>
<input type="password" class="form-control ng-pristine ng-valid" ng-model="password">
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="">Login</button>
</div><br/>
<span class="text-danger">{{ error }}</span>
</form>
角JS:
var app = angular.module('logapp',['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/login',{
templateUrl : "login.html",
controller : "loginctrl"
})
.when('/home',{
templateUrl : "home.html",
controller : "homectrl"
});
$routeProvider.otherwise({ redirectTo: '/login'});
});
app.controller('credientials',['$scope','$route','$http','$window',function($scope,$route,$http,$window){
$scope.templates =
[
{ url: 'login.html' },
{ url: 'practice.html'}
];
$scope.template = $scope.templates[0];
$scope.loginform = function (username, password) {
if ( username === 'admin' && password === '1234') {
authentication.isAuthenticated = true;
$scope.template = $scope.templates[1];
$scope.user = username;
} else {
$scope.error = "Invalid username and password";
};
};
app.factory('authentication', function() {
return {
isAuthenticated: false,
user: null
}
});
}]);
您忘了将工厂的"身份验证"注入控制器。
app.controller('credientials',['$scope','$route','$http','$window',function($scope,$route,$http,$window,authentication){
您必须使用$范围作为用户名和密码
$scope.username === 'admin' && $scope.password === '1234'
,然后您会看到工厂中的变量iSauthenticated将为true
我在这里更改了您的代码
您需要将用户名和密码放在范围上。也许这会更好:
$scope.username = "";
$scope.password = "";
$scope.loginform = function () {
if ( $scope.username === 'admin' && $scope.password === '1234') {
您应该真正考虑此教程
https://docs.angularjs.org/tutorial