注射角度指令

时间:2015-12-22 05:22:31

标签: javascript angularjs regex directive

我正在努力使用角度指令,控制器工作正常,但我不能使指令被注入。

以下是Angular Script:

(function () {
'use strict';

angular
    .module('iziCooker')
    .controller('RegistrationController', RegisterController)
    .directive('registrationValidation', registrationValidation);

RegisterController.$inject = ['UserService', '$location', '$rootScope', 'FlashService'];
function RegisterController(UserService, $location, $rootScope, FlashService) {
    var vm = this;

    vm.register = register;
    vm.CheckUser = CheckUser;

    function register() {
            vm.dataLoading = true;
            UserService.Create(vm.user)
                .then(function (response) {
                    if (response.success) { //
                        FlashService.Success('Registration successful', true);
                        $location.path('/home');
                    } else {
                        FlashService.Error(response.message);
                        vm.dataLoading = false;
                    }
                });
    }

    function CheckUser($event) {
        var usernameinput = $event.target;
        var username = usernameinput.value;

        if (username != '') {
            UserService.GetByUsername(username)
                .then(function (response) {
                    if (response.success) {
                        //username.setCustomValidity("");
                        alert("Usuario libre!");
                    } else {
                        alert("Usuario en uso!");
                        //username.setCustomValidity("El nombre de usuario ingresado ya se encuentra en uso.");
                    }
                });
        }
    }
}

registrationValidation.$inject = ['$scope'];
function registrationValidation($scope) {
    $scope.emailregex = "(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}";
    return {
        restrict: "E",
        replace: true,
        template: "<div>Here I am to save the day</div>"
    }
}})();

我想使用该指令来验证注册表单。设置密码和电子邮件的正则表达式;验证确认密码和电子邮件;等

我试图从指令中返回一个HTML对象,但它也没有。

我想知道我是否有语法错误或者我是否遗漏了某些内容。 我没有收到任何类型的错误,控制器注入时没有任何问题,也没有说明该指令。

我从视图中添加了html代码,并使用&#34;标记了指令返回的HTML标记。 ***&#34;。

>
<div class="inicio-container">
    <div class="row">
        <div class="col-lg-6 col-lg-offset-3">
            <div class="col-lg-12 caja">
                <div class="row">
                    <div class="titulo-nivel">
                        &iexcl;Registrate y comenzá con tu camino a la gastronomía!
                    </div>
                    ***<registrationValidation></registrationValidation>***
                </div>
                <div class="row">
                    <form class="col-lg-6 col-lg-offset-3" name="registrationForm" ng-submit="vm.register()" role="form" novalidate>
                        <div class="form-group" ng-class="{ 'has-error': registrationForm.name.$touched && registrationForm.name.$invalid }">
                            <label for="name">Nombre</label>
                            <input type="text" class="form-control" id="input-name" name="name" placeholder="Ingresá tu nombre" ng-model="vm.user.name" ng-minlength="2" ng-maxlength="100" ng-required="true" ng-model-options="{ updateOn: 'blur' }">
                            <div class="help-block" ng-messages="registrationForm.name.$error" ng-if="registrationForm.name.$touched">
                                <p ng-message="minlength">El nombre que ingresaste es muy corto.</p>
                                <p ng-message="maxlength">El nombre que ingresaste es muy largo.</p>
                                <p ng-message="required">¡Tenés que completar tu nombre!</p>
                            </div>
                        </div>
                        <div class="form-group" ng-class="{ 'has-error': registrationForm.lastname.$touched && registrationForm.lastname.$invalid }">
                            <label for="last-name">Apellido</label>
                            <input type="text" class="form-control" id="input-lastname" name="lastname" placeholder="Ingresá tu apellido" ng-model="vm.user.lastname" ng-minlength="2" ng-maxlength="100" ng-required="true" ng-model-options="{ updateOn: 'blur' }">
                            <div class="help-block" ng-messages="registrationForm.lastname.$error" ng-if="registrationForm.lastname.$touched">
                                <p ng-message="minlength">El apellido que ingresaste es muy corto.</p>
                                <p ng-message="maxlength">El apellido que ingresaste es muy largo.</p>
                                <p ng-message="required">¡Tenés que completar tu apellido!</p>
                            </div>
                        </div>
                        <div class="form-group" ng-class="{ 'has-error': registrationForm.birthdate.$touched && registrationForm.birthdate.$invalid }">
                            <label for="birthdate">Fecha de nacimiento</label>
                            <input type="text" class="form-control" id="input-birthdate" name="birthdate" placeholder="Ingresá tu fecha de nacimiento" ng-model="vm.user.birthdate" ng-required="true" onfocus="(this.type = 'date')">
                            <div class="help-block" ng-messages="registrationForm.birthdate.$error" ng-if="registrationForm.birthdate.$touched">
                                <p ng-message="required">¡Tenés que completar tu fecha de nacimiento!</p>
                            </div>
                        </div>
                        <div class="form-group" ng-class="{ 'has-error': registrationForm.email.$touched && registrationForm.email.$invalid }">
                            <label for="email">Dirección de correo electrónico</label>
                            <input type="email" class="form-control" id="input-email" name="email" placeholder="Ingresá tu dirección de email" ng-model="vm.user.email" ng-required="true" ng-model-options="{ updateOn: 'blur' }">
                            <div class="help-block" ng-messages="registrationForm.email.$error" ng-if="registrationForm.email.$touched">
                                <p ng-message="required">¡Tenés que completar tu email!</p>
                                <p ng-message="email">¡Email incorrecto!</p>
                            </div>
                        </div>
                        <div class="form-group" ng-class="{ 'has-error': registrationForm.confirmemail.$touched && registrationForm.confirmemail.$invalid }">
                            <label for="email">Confirmar dirección de correo electrónico</label>
                            <input type="email" class="form-control" id="input-confirmemail" name="confirmemail" placeholder="Ingresá la confirmación de email" ng-model="vm.user.confirmemail" ng-required="true" ng-model-options="{ updateOn: 'blur' }">
                            <div class="help-block" ng-messages="registrationForm.confirmemail.$error" ng-if="registrationForm.confirmemail.$touched">
                                <p ng-message="required">¡Tenés que completar la confirmación de email!</p>
                                <p ng-message="email">¡Mail con formato incorrecto!.</p>
                            </div>
                        </div>
                        <div class="form-group" ng-class="{ 'has-error': registrationForm.username.$touched && registrationForm.username.$invalid }">
                            <label for="username">Nombre de usuario</label>
                            <input type="text" class="form-control" id="input-username" name="username" placeholder="Ingresá tu nombre de usuario" ng-model="vm.user.username" ng-required="true"> <!--ng-blur="vm.CheckUser($event)"-->
                            <div class="help-block" ng-messages="registrationForm.username.$error" ng-if="registrationForm.username.$touched">
                                <p ng-message="required">¡Tenés que completar tu nombre de usuario!.</p>
                            </div>
                        </div>
                        <div class="form-group" ng-class="{ 'has-error': registrationForm.password.$touched && registrationForm.password.$invalid }">
                            <label for="password">Contraseña</label>
                            <input type="password" class="form-control" id="input-password" name="password" placeholder="Ingresá tu contraseña" ng-pattern="emailregex" ng-model="vm.user.password" ng-required="true">
                            <div class="help-block" ng-messages="registrationForm.password.$error" ng-if="registrationForm.password.$touched">
                                <p ng-message="required">¡Tenés que completar tu contraseña!.</p>
                                <p ng-message="pattern">La contraseña debe contar con al menos un número, una letra mayúscula y minúscula y 8 o más caracteres.</p>
                            </div>
                        </div>
                        <div class="form-group" ng-class="{ 'has-error': registrationForm.confirmpassword.$touched && registrationForm.confirmpassword.$invalid }">
                            <label for="confirm-password">Confirmar contraseña</label>
                            <input type="password" class="form-control" id="input-confirmpassword" name="confirmpassword" placeholder="Ingresá la confirmación de contraseña" ng-pattern="emailregex" ng-model="vm.user.confirmpassword" ng-required="true">
                            <div class="help-block" ng-messages="registrationForm.confirmpassword.$error" ng-if="registrationForm.confirmpassword.$touched">
                                <p ng-message="required">¡Tenés que completar la confirmación de la contraseña!.</p>
                                <p ng-message="pattern">La contraseña debe contar con al menos un número, una letra mayúscula y minúscula y 8 o más caracteres.</p>
                            </div>
                        </div>
                        <div class="form-actions">
                            <input type="submit" class="login" value="¡Registrate ahora!" ng-disabled="registrationForm.$invalid"></> 
                            <img ng-if="vm.dataLoading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:0)

在指令中,$scope被注入到链接前或链接后的函数中,而不是顶级指令定义。

以下是registrationValidation指令的更新版本,该指令将emailregex放在范围内。

registrationValidation.$inject = [];
function registrationValidation() {
    return {
        scope: true,  // Create a new child scope.
        restrict: "E",
        template: "<div>Here I am to save the day</div>",
        link: function postLink($scope, $element, attrs){
            // Get access to the directive's scope, element and attributes.

            $scope.emailregex = "(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}";
        }
    }
}

注意:我还设置了scope: true,因此正则表达式被添加到新的子范围,并且不会干扰同一父范围中可能存在的其他指令。

我还删除了自已弃用以来的replace: true,并将在更高版本的Angular中删除。

答案 1 :(得分:0)

将指令元素 if(FBSDKAccessToken.currentAccessToken() != nil) { } 更改为<registrationValidation></registrationValidation>

working demo