我正在通过 YouTube 教程系列学习 Angular。在本教程中,您创建用户名和密码输入,然后使用 Controller 和 ngRoute 在使用成功的凭据时打开 dashboard.html 页面。问题是单击按钮时,无论是否输入了正确的凭据,都没有任何反应。一切都在教程中进行,我已经对代码进行了三次彻底检查,我的代码看起来就像教程中的代码。不过,我确定我一定遗漏了一些东西。
我的想法:
点击事件触发有问题,所以我调用该函数的方式可能有问题?
本教程使用较旧的 Angular 版本 (1.3.14),也许情况有所改变?我使用的是 1.4.9,但我查找了 ng-click 指令的 api 数据,一切似乎都很好。我也尝试过使用旧版本无济于事。
我在 ngRoute 上做错了什么,可能是 $scope 误用?
我正在插入下面的所有代码。感谢您的关注!
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Place Title Here</title>
<meta charset = "utf-8"/>
<meta http-equiv="X-UA-compatible" content="IE-edge, chrome=1">
<meta name = "viewport" content = "width = device - width, initial-scale = 1.0"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-view></div>
</body>
</html>
login.html
<div ng-controller="loginCtrl"></div>
<form action="/" id="myLogin">
Username: <input type="text" id="username" ng-model="username"><br>
Password: <input type="password" id="password" ng-model="password"><br>
<button type="button" ng-click="submit()">Login</button>
</form>
controller.js
var app = angular.module('mainApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html'
})
.when('/dashboard', {
templateUrl: 'dashboard.html'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('loginCtrl', function($scope, $location) {
$scope.submit = function() {
var uname = $scope.username;
var password = $scope.password;
if($scope.username == 'admin' && $scope.password == 'admin') {
$location.path('/dashboard');
}
else {
alert('Nope')
}
};
});
dashboard.html
Welcome User.
最佳答案
你的 form
需要在带有 ng-controller
的 div 中
<div ng-controller="loginCtrl">
<form action="/" id="myLogin">
Username: <input type="text" id="username" ng-model="username"><br>
Password: <input type="password" id="password" ng-model="password"><br>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
否则它将无法访问 submit()
函数。
关于javascript - ng-click 事件似乎不会在简单的 Angular 应用程序中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516606/