2016-08-17 85 views
1

我试图建立一个角的形式,但我是新与它,所以我需要一些帮助:)角:检查值NG-模糊

我有一个字段“电子邮件”这应该是在用户离开该字段时进行检查。我的控制器中的一个函数应该检查输入值是否已经存在于数据库中(ajax/http)。

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

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

HTML(玉)

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){ 

     }); 

    } 
+0

,而不是玉代码,就可以显示生成的HTML代码?何时你的'$ scope.user'对象被初始化? –

+0

@NVO:试试我的代码,我添加了正在运行的剪辑 –

回答

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){ 

     }); 

    } 
+0

仍然得到'undefined'... – NVO

+0

我已经更新了我的答案。这里的问题是当您将模型绑定到电子邮件输入时(type =“email”)。只有您输入的值是有效的电子邮件时,模型中的值才会更新。 –

+0

Aaah,但这很好,我有另一个检查有效的电子邮件地址。这也会阻止该功能被称为“太多” – NVO

2

请试试这个剪断

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) 
+0

仍然一样。当我将ng-blur更改为ng-change时,我在控制器中获得了一些值,但离开该字段时该事件不会被触发。 – NVO

+0

为我提供你的代码的jsfiddle –