角度:检查值ng-blur

时间:2016-08-17 09:06:57

标签: javascript angularjs

我正在尝试在Angular中构建一个表单,但我是新的,所以我需要一些帮助:)

我有一个字段'email',当用户离开该字段时应该检查该字段。我的控制器中的一个函数应检查输入的值(如果它已存在于数据库中(ajax / http))。

我找到了'ng-blur'功能,并在我的控制器中创建了一个功能来检查电子邮件。但是,$ scope.user.email是未定义的,我不知道我做错了什么。有人可以帮帮我吗?

到目前为止,这是我的代码:

HTML(jade)

p.claim-text Email
abbr.required.claim-text(title='required') *
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', value='', name='email', ng-model='user.email', ng-blur='checkEmail()' required)
p(ng-show="registerForm.email.$invalid && !registerForm.email.$pristine").help-block Invalid emailadres
p(ng-show="emailExists").help-block User exists! Click here to login

控制器功能

$scope.checkEmail = function(){
        console.log($scope.user.email);
        $http({
            method: 'GET',
            url: '[someurl]',
            data: $scope.user.email,
        }).then(function successCallback(response){
            //if response is true, set emailExists to true;
        }, function errorCallback(response){

        });

    }

2 个答案:

答案 0 :(得分:3)

请尝试此剪辑

var myApp = angular.module('myApp',[]);

myApp.controller('GreetingController', ['$scope','$http', function($scope, $http) {
  //You can check POST at server side to get the entered email
  $scope.checkEmail = function(email){
  //REMOVE THIS LINE
  console.log(email);return false;
        $http({
            method: 'POST',
            url: '[someurl]',
            data: email,
        }).then(function successCallback(response){
            //if response is true, set emailExists to true;
        }, function errorCallback(response){

        });

    }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<!--HTML -->
<div ng-app="myApp" ng-controller="GreetingController">
<input type="text" ng-blur="checkEmail(email)" ng-model="email"/>
</div>

OR
<!--JADE -->
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', name='email', ng-model='user.email', ng-blur='checkEmail(user.email)' ng-init="user.email=''" required)

答案 1 :(得分:1)

您可以将电子邮件传递给checkEmail函数

input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', value='', name='email', ng-model='user.email', ng-blur='checkEmail()' required)

然后在控制器中你只需要从参数

获取电子邮件
$scope.checkEmail = function(){
        console.log($scope.user.email);
        $http({
            method: 'GET',
            url: '[someurl]',
            data: $scope.user.email,
        }).then(function successCallback(response){
            //if response is true, set emailExists to true;
        }, function errorCallback(response){

        });

    }