为什么名称和密码未定义? 我在他们身上使用了ng-model ......
<form class="login" name="form">
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="name">Name: </label>
<input type="text" ng-model="name" id="name" class="form-control" placeholder="Nitzan">
</div>
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="password">Password: </label>
<input type="password" ng-model="password" id="password" class="form-control" placeholder="1234">
<p class="help-block" ng-if="isInvalidLogin">Name or password are wrong!</p>
</div>
<button type="submit" class="btn btn-block btn-lg btn-success login-btn" ng-click="login()">Login</button>
</form>
在控制器中:
$scope.login = function () {
usersService.get($scope.name, $scope.password).then(function success(result){
$scope.currentUser = result;
}, function error() {
$scope.isInvalidLogin = true;
});
};
查看plunker: http://plnkr.co/edit/QD3vtil3w9pd4d1TGl9v?p=preview
答案 0 :(得分:1)
您的问题是因为ng-if
指令正在从当前作用域创建子作用域。因此$ scope.name&amp; $ scope.password在$scope.login
函数中未定义。
我建议您为user
创建一个对象,该对象最初为user={}
空白,或者您可以使用ng-init
在html上执行此操作,然后将其放在mainController
内{1}}以便父级可以直接访问它而不用$parent.
符号。
将name
和password
放在用户对象中。
<强> HTML 强>
<div ng-init="user={}">
<div class="container login-div" ng-if="!currentUser">
<form class="login" name="form" ng-submit="login()">
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="name">Name:</label>
<input type="text" ng-model="user.name" id="name" class="form-control" placeholder="Nitzan">
</div>
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="password">Password:</label>
<input type="password" name="test" ng-model="user.password" id="password" class="form-control" placeholder="1234">
<p class="help-block" ng-if="isInvalidLogin">Name or password are wrong!</p>
</div>
<button type="submit" class="btn btn-block btn-lg btn-success login-btn">Login</button>
</form>
</div>
</div>
<强> CODE 强>
$scope.login = function () {
alert("Name "+ $scope.user.name +"& password is " +$scope.user.password)
//usersService.get($scope.name, $scope.password).then(function success(result){
// $scope.currentUser = result;
//}, function error() {
// $scope.isInvalidLogin = true;
//});
};
<强>更新强>
否则,您需要添加更改ng-model以将此范围引用到父范围,如
<强> HTML 强>
名称ng-model="$parent.name"
密码ng-model="$parent.password"
<强> CODE 强>
$scope.login = function () {
alert("Name "+ $scope.name +"& password is " +$scope.password)
//usersService.get($scope.name, $scope.password).then(function success(result){
// $scope.currentUser = result;
//}, function error() {
// $scope.isInvalidLogin = true;
//});
};
希望这可以帮到你。感谢。