AngularJS中自定义指令中的范围,用于检查DB中是否已存在值

时间:2017-10-09 13:57:45

标签: angularjs email angularjs-directive controller angularjs-scope

我的自定义指令中存在范围问题,用于检查数据库中是否已存在电子邮件。实际上,AJAX查询检索的结果不会在范围内(以及我的模板中)返回。

为了实现这一点,我遵循一个解决方案来检查本主题中定义的数据库中是否已存在电子邮件angularjs: custom directive to check if a username exists

在我的应用程序中,用户可以注册5个电子邮件。当用户在字段中输入电子邮件时,将正确执行查询以检查电子邮件是否已在数据库中使用。该查询以JSON格式返回具有相同电子邮件的人员

此处我的控制器

// MY CUSTOM DIRECTIVE FOR CHECKING IF EMAIL IS ALREADY USED
app.directive('emailAvailable', function($timeout, $q, $http, ContactService) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) { 
            model.$asyncValidators.emailExists = function() {   
                email= elm.val();
                return ContactService.searchContactByEmail(email).success(function(con){
                    $timeout(function(){
                    if(email.length >0){
                        if(con.length >0){
                            model.$setValidity('emailExists', false);
                            scope.emailAlreadyExist='true';
                            scope.con = con; 
                            console.log('NB: ' + scope.con.length); // IT'S WORKING
                            console.log("email exist: " + scope.emailAlreadyExist); // IT'S WORKING TOO                         
                        }else{
                            model.$setValidity('emailExists', true);
                            scope.emailAlreadyExist='false';    
                            scope.con = null;       
                            alert('jjjjj' + con);

                            console.log("email NOT EXIST : " + scope.emailAlreadyExist);                            
                        }
                    }
                    }, 1000);
                });

            };
        }
    } 
});


app.controller('ctrlAddContacts', function ($scope, MyTextSearch, ContactService){

    $scope.emailAlreadyExist = false;


    // ALLOW TO HAVE SEVERAL EMAILS
    $scope.emails = [
    {
    }];
    $scope.log = function() {
      console.log($scope.emails);
    };
    $scope.add = function() {
        var dataObj = {email:''};       
        $scope.emails.push(dataObj);
    }

    ...........
});

这里我的工厂

app.factory('ContactService', function($http){

    var factory={};

    // CALL COLDFUSION FUNCTION --> GET JSON RESULTS ON PERSONS DATA     
    factory.searchContactByEmail=function(string){
        if (string){
            chaine='http://myapp/contacts.cfc?method=searchContactByEmail&contactEmail=' + string;      
        }else{
            chaine='';      
        }
        return $http.get(chaine);
    };  

    return factory;

})

此处我的模板

<div ng-repeat="(key, email) in emails | limitTo : 5" style="z-index:6">

  <div class="form-group">

    <span ng-switch="$index">
        <label ng-switch-when="0" for="txtEmail" class="col-sm-2 control-label">Main email</label>
        <label ng-switch-default for="txtEmail" class="col-sm-2 control-label">Email  {{$index+1}}</label>
    </span> 

    <div class="col-sm-9" ng-switch="$index">

        <input ng-switch-when="0" type="email" class="form-control"
        name="txtEmail_{{$index}}" maxlength="100" placeholder="Enter main email"
        ng-model="contact.EMAIL"
        email-available emailexist = "emailAlreadyExist " > 


        <input ng-switch-default type="email" class="form-control" 
        name="txtEmail_{{$index}}" maxlength="100" placeholder="Enter Email {{$index+1}}" 
        ng-model="contact['EMAIL_'+$index]" 
        email-available emailexist = "emailAlreadyExist " >     

        <!--------------------- PROBLEM FOR DISPLAYING THE CONTACTS PERSON WITH THE EMAIL --------------------- START --------------------->
        {{con}} 
        <!--------------------- PROBLEM FOR DISPLAYING THE CONTACTS PERSON WITH THE EMAIL ---------------------- END ---------------------->

        <div ng-show="ContactForm['txtEmail_' + $index].$dirty && ContactForm['txtEmail_' + $index].$error.emailExists" class="alert alert-info" role="alert" style="margin-top:10px;">
        <span class="glyphicon glyphicon-alert" aria-hidden="true"></span>
        <span class="sr-only">Error:</span>
            This email is already used <!--- CORRECTLY DISPLAYED WHEN THE EMAIL IS ALREADY USED IN THE DB --->

            <!--------------------- PROBLEM FOR DISPLAYING THE CONTACTS PERSON WITH THE EMAIL --------------------- START --------------------->
            <ul id="contacts_list">
                <li ng-repeat=" contact in con" style="position:relative; z-index:25">
                    <div angular-popover direction="right" template-url="template/popover.html" mode="mouseover">
                        <a href="#/view-contacts/{{contact.id}}">{{ contact.lastname }} {{ contact.firsttname }}</a> 
                    </div>
                </li>
            </ul>
            <!--------------------- PROBLEM FOR DISPLAYING THE CONTACTS PERSON WITH THE EMAIL ---------------------- END ---------------------->
        </div>

    </div>

    <div  class="col-sm-1" ng-show="$index == 0">
        <a href="" ng-click="add()" ng-show="emails.length<5" class="inline btn btn-primary icon_email">
        <span class="glyphicon glyphicon-plus icon2"></span><span class="addButton">Add</span>
        </a>
    </div>  

  </div>

</div>

你能帮我解决这个问题吗?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

(至少在Angular 1.6+中)$http可以返回一个promise,但你负责从中返回实际数据。一个更简单的例子就是:

return $http.get(url).
then((res) => {
  return res.data;
});

请注意用于承诺和数据的返回

在复杂的示例中很难看到,但{{con}}为空的原因是因为您从未从异步回调中返回它。