2013-05-11 22 views
1

我试图使用http://keith-wood.name/realPerson.html jQuery插件创建一个验证码指令。在指令中将jquery生成的隐藏字段绑定到angularjs模型

我是相对较新的angularjs,似乎无法找到一种方法来做到这一点。基本上我想要一个验证码来验证一个人正在注册他们的帐户。调用element.realperson()将生成一个隐藏的输入字段,其中有一些散列值,我需要将它与在服务器端输入的输入进行比较。所以如果我把这个非常基本的和不完整的指令称为它,它会将newUser.captchaInput模型绑定到输入表单,但是我不能为我的生活弄清楚如何获取隐藏的字段值$(' #captcha_hash')。val()并以某种方式将它包含在表单数据中。理想的情况是newUser.captchaHash。

angular.module('vah').directive("captcha", -> 
    restrict: "A" 
    require: '?ngModel' 
    link: (scope, element, attrs, ngModel) -> 
    return if !ngModel 

    optionsObj = { 
     length: 5 
    } 

    element.realperson(optionsObj) 

    # need to bind $('#captcha_hash').val() to a newUser.captchaHash model, or 
    add the model to that generated input field. 

) 

<input captcha id="defaultReal" ng-model="newUser.captchaInput"> 

我确信有一个简单的解决方案,并希望有任何帮助。

回答

0

工作代码,感谢来自不同编程论坛上某人的帮助。这绝对不是理想的,我有很多学习要做,但这是有效的。

angular.module('vah').directive("captcha", ($timeout, $parse) -> 
    restrict: "A" 
    require: '?ngModel' 
    link: (scope, element, attrs, ngModel) -> 
    return if !ngModel 

    optionsObj = { 
     length: 5 
    } 

    $timeout(-> 
     attrs.foo = $('#captcha_hash') 
     hashSet = $parse(attrs.ngModel).assign 
     scope.$watch(attrs.foo.val(), (newVal) -> 
     hashSet(scope, newVal) 
    ) 
    , 300) 
    element.realperson(optionsObj) 

) 

而且,我会包括这个特殊的验证码的散列的Ruby代码,因为我遇到了与Bignum的和红宝石的问题相比,它在JavaScript中所做的那样,或者它们的PHP/Java的例子。

module CaptchaHashing 
    module ClassMethods 
    def rp_hash(value) 
     hash_value = 5381 
     value = value.upcase 
     value.chars.each do |c| 
     hash_value = ((left_shift_32(hash_value, 5)) + hash_value) + c.ord 
     puts hash_value 
     end 
     hash_value 
    end 

    def left_shift_32 x, shift_amount 
     shift_amount &= 0x1F 
     x <<= shift_amount 
     x &= 0xFFFFFFFF 

     if (x & (1<<31)).zero? 
     x 
     else 
     x - 2**32 
     end 
    end 

    end 

    def self.included(receiver) 
    receiver.extend ClassMethods 
    end 
end 

def self.valid_captcha?(captcha_hash, captcha_input) 
    if captcha_hash.present? && captcha_input.present? 
     rp_hash(captcha_input) == captcha_hash 
    else 
     false 
    end 
    end 

祝你好运!

1

如果你喜欢reCaptcha,你可以尝试使用VividCortex/angular-recaptcha

+0

意外downvote,对不起! – 2013-07-05 11:18:57

+0

没关系@MichaelRobinson。您可以通过再次单击箭头来撤消它:) – 2013-08-20 23:50:05

+0

投票被锁定,除非答案被编辑(感谢提示,尽管:P) – 2013-08-21 01:57:37