添加指令,绑定将不起作用

时间:2015-06-03 13:50:46

标签: javascript angularjs ionic-framework

我是Angular的新手,我正在创建一个带有angularjs和离子框架的移动应用程序, 我有一个输入(项目名称),我有一个指令,以验证项目名称是否已经存在,该指令将禁用数据绑定。 请帮忙。

 <input type="text" name="projectname" projectname-available    id="projectname" ng-minlength="3"
ng-maxlength="20" ng-pattern="projectPattern"  required   ng-model="form.projectname" >
<div class="error-container" ng-show="authorizationForm.projectname.$invalid && authorizationForm.projectname.$touched"  ng-messages="authorizationForm.projectname.$error"   ng-messages-include="templates/error-list.html">
            <div class="error" ng-message="required">
                <i class="ion-information-circled"></i>
                This field is invalid!
            </div>
            <div class="error" ng-if="authorizationForm.$error.projectnameExists" >
                <i class="ion-information-circled"></i>
                Project name exists already
            </div>

        </div>

这是指令代码

.directive('projectnameAvailable', function($timeout, $q,$cordovaSQLite) {
return {
 restrict: 'AE',
 require: 'ngModel',
 link: function(scope, elm, attr, model) {
   model.$asyncValidators.projectnameExists = function(projectName) {
     //here you should access the backend, to check if username exists
     //and return a promise
     query = "SELECT * FROM project WHERE name = ? ";
        $cordovaSQLite.execute(db, query, [projectName]).then(function(res1) {

            if(res1.rows.length>0) {
               exist = true;
               console.log('projet trouvé');
              }
            else
            {
            console.log('projet non trouvé');
             return exist = false;
             }
             }, function (err) {
                 console.error(JSON.stringify(err));
                }
             );
     var defer = $q.defer();
     $timeout(function(){
       model.$setValidity('projectnameExists', !exist);
       defer.resolve;
     }, 2000);
     return defer.promise;
   };
 }
}

});

调试

 console.log('nom projet '+$scope.form.projectname );

我得到nom projet undefined

plunker

1 个答案:

答案 0 :(得分:1)

你快到了。这是一个有效的插件:http://plnkr.co/edit/qbAHG4dvDAHUOBzKbo5o?p=preview

我刚刚在app.js中更改了一行:

defer.resolve;

到此:

defer.resolve(projectName);

玩得开心。