登录存在检查Angular JS

时间:2014-07-15 13:10:49

标签: javascript angularjs

我正在写一个带有角度的注册表单,但我还是这个框架的新手。 我得到了密码匹配验证:

<div class="form-group">
    <label for="uPassword">Password:</label>
    <div>
        <input type="password" class="form-control" name="password" Placeholder="Password" id="uPassword" ng-model="user.newPassword" data-ng-class="{'ng-invalid':userForm.pwdConfirm.$error.match}" ng-required="!user.userId"/>
    </div>
 </div>
 <div class="form-group">
    <label for="uConfirm">Confirm: </label>
         <input type="password" data-match="user.newPassword" name="pwdConfirm" Placeholder="Confirm Password" id="uConfirm" ng-model="user.passwordConfirm" ng-model-options="{ updateOn: 'blur' }" ng-required="user.userId > 0  && userForm.password.$dirty || !user.userId"/>
         <div ng-show="userForm.pwdConfirm.$dirty && userForm.pwdConfirm.$error.match">Password and Confirm do not match!</div>
 </div>

但检查登录可用性时遇到问题。这是我登录的输入:

<div>
    <input type="text" placeholder="User" name="userLogin" id="uLogin" ng-model="user.login" required/>
</div>

已经使用过的登录通过REST传递给我的UserCreateCtrl控制器:

    $scope.allUsers = User.all;
    for(var i=0; i<$scope.allUsers.length; i++){
        console.info($scope.allUsers[i].login);
    }

有没有办法像使用密码一样使用与allUser数组匹配的数据?我现在真的很难受。 感谢您的回复,

2 个答案:

答案 0 :(得分:1)

我总是喜欢指令方式,它可以让你用各种工具控制你的元素。我使用这个自定义指令进行密码验证:

module.directive('anMatch', function () {
return {
    require: 'ngModel',
    restrict: 'A',
    scope: {
        anMatch: '='
    },
    link: function(scope, elem, attrs, ctrl) {
        scope.$watch(function() {
            return (ctrl.$pristine && angular.isUndefined(ctrl.$modelValue)) || scope.anMatch === ctrl.$viewValue;
        }, function(currentValue) {
            ctrl.$setValidity('match', currentValue);
        });
    }
};
});

html用法是:

密码:

<input type="password" required ng-model="user.password">

确认密码:

<input data-an-match="user.password" type="password" ng-model="user.rpassword">

至于用户列表。同样,您可以编写自定义指令来为您验证它。

module.directive('userMatch', ['UserService', function (UserService) {
return {
    require: 'ngModel',
    restrict: 'A',
    scope: {
        anMatch: '='
    },
    link: function(scope, elem, attrs, ctrl) {
        scope.$watch(function() {
            var userExist = true;
            var users = UserService.AllUsers;
            for (i =0; users.lenght; i++) {
                if (ctrl.$viewValue == users[i]) {
                    userExist = false;
                    break;
                }

            }    
            return userExist;
        }, function(currentValue) {
            ctrl.$setValidity('uservalid', currentValue);
        });
    }
};
}]);

最后一件事,你可能想要MD5服务器上的值而不是MD5用户输入和匹配,而不是返回用户名。为了安全礼仪。

详细了解DirectivesAngular-MD5

答案 1 :(得分:0)

角度js的力量仍然让我惊讶!这是一个带过滤器的解决方案。

{{(allUsers | filter:user.login:true).length==0?"Unique Name":"Username taken"}}

allUsers是包含所有用户名的数组。