有兩個ng控制器,每個都有一個ng單擊。不能在同一頁上有2個ng單擊
如果我將下面的代碼設置爲兩個ng-click腳本,那兩個按鈕將不起作用。但是,如果我只設置了任何一個ng-click腳本,該按鈕就起作用。
我該如何解決?
<body ng-app="myapp">
<div ng-controller="loginController">
<h3>Login</h3>
<form class="login" role="form">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" ng-model="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" ng-model="password">
</div>
<button type="submit" ng-click="login()" class="btn btn-default">Login</button>
</form>
</div>
<div ng-controller="registerController">
<h3>Register</h3>
<form class="register" role="form">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" ng-model="emailR">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" ng-model="pwdR">
</div>
<div class="form-group">
<label for="name">Your Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter your name" ng-model="nameR">
</div>
<button type="submit" ng-click="register()" class="btn btn-default">Register</button>
</form>
</div>
<script>
var api = ""
angular.module("myapp", []).controller("loginController", function($scope, $http) {
$scope.login = function(){
if(!isEmpty($scope.email) || !isEmpty($scope.password)){
var loginInfo = api + "login/" + $scope.email + "/" + $scope.password;
var responsePromise = $http.get(loginInfo);
responsePromise.success(function(data, status, headers, config) {
var msg = data.result;
alert(msg);
top.location.reload();
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX fail!");
});
}
}
});
angular.module("myapp", []).controller("registerController", function($scope, $http) {
$scope.register = function(){
if(!isEmpty($scope.emailR) || !isEmpty($scope.pwdR || !isEmpty($scope.nameR))){
var registerInfo = api + "register/" + $scope.emailR + "/" + $scope.pwdR + "/" + $scope.nameR; alert(registerInfo);
var responsePromise = $http.get(registerInfo);
responsePromise.success(function(data, status, headers, config) {
var msg = data.result;
alert(msg);
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX fail!");
});
}
}
});
您可能想用別名命名您的控制器,然後在調用ng-click()方法時將此別名用作前綴。例如:ng-controller =「loginController as ctrl」,然後ng-click =「ctrl.login()」當然可以將別名更改爲任何適合的名稱。通常以單數和小寫形式表示控制器的名稱。這樣你甚至可以嵌套控制器。並在控制器上的方法的定義使用:this.login,而不是$ scope.login – Jorge