Dre*_*rew 1 validation coffeescript angularjs angularjs-directive
所以,我需要一个验证器来检查以确保我的password_confirmation
字段与我的password
字段匹配.我最终得到了以下指令:
指示
@app.directive 'matches', ->
require: 'ngModel', #Needed for validation bits
scope: { matched_value: '=matches' } #Looks up the value of the scope element we're matching against and keeps it bound
link: (scope, elem, attrs, ctrl) ->
ctrl.$parsers.unshift (view_value) -> #Add a new parser that updates the validity
ctrl.$setValidity(elem.attr('name'), view_value == scope.matched_value)
Run Code Online (Sandbox Code Playgroud)
形成
<form name="form">
<input ng-model="new_user.password" name="password">
<input ng-model="password_confirmation" name="password_confirmation" matches="new_user.password">
</form>
Run Code Online (Sandbox Code Playgroud)
当用户从上到下使用表单时,这很好用.然而,如果他们继续改变password
之后他们已经填补了password_confirmation
它,那么它就不会像它应该的那样变得无效.
我的第一个stab看起来添加了一个$watch
er指令,但我似乎无法获得新password_confirmation
输入的正确值.
带观察者的指令(CoffeeScript)
@app.directive 'matches', ->
require: 'ngModel',
scope: { matched_value: '=matches' }
link: (scope, elem, attrs, ctrl) ->
ctrl.$parsers.unshift (view_value) ->
ctrl.$setValidity(elem.attr('name'), view_value == scope.matched_value)
scope.$watch attrs['watches'], ->
ctrl.$setValidity(elem.attr('name'), ctrl.$view_value == scope.matched_value)
Run Code Online (Sandbox Code Playgroud)
但ctrl.$view_value
总是未定义,让我相信我做错了.
我怎样才能获得实际价值?这是建立这种反向关系的正确方法吗?有一个更好的方法吗?
https://github.com/wongatech/angular-confirm-field是一个很好的项目.
这里的例子http://wongatech.github.io/angular-confirm-field/
下面的代码显示了具有已实现功能的2个输入字段
<input ng-model="email" name="my-email" />
<input ng-confirm-field ng-model="emailconfirm" confirm-against="email" name="my-email-confirm"/>
Run Code Online (Sandbox Code Playgroud)
该指令与其他实现的不同之处在于它使用$ parsers和$ watch来确保仅在视图值有效时更新模型属性.
归档时间: |
|
查看次数: |
1068 次 |
最近记录: |