我正在学习AngularJS中指令的使用。我有一个包含输入密码的password.html文件,然后创建了自己的指令“ passwordRequirement”以强制用户在创建用户时满足这些要求。这是password.html的代码:
<div class="form-group">
<label for="user_password">Password</label>
<input type="password" data-ng-change="passwordChanged();" data-ng-model="user.password" class="form-control" id="user_password" name="user_password"
placeholder="Password" required>
<div data-ng-show="enteredPassword">
<h4>For your security, the password needs to meet the following requirements</h4>
<password-requirement binding="passwordContainLowercase">Password must contain at least a lowercase character</password-requirement>
<br>
<password-requirement binding="passwordContainUpperCase">Password must contain at least uppercase character</password-requirement>
<br>
<password-requirement binding="passwordLengthValid">Password length must be between 12 and 20 characters</password-requirement>
<br>
<password-requirement binding="passwordContainDigit">Password must contain at least a digit</password-requirement>
</div>
</div>
由于每个需求都绑定到范围内的不同属性,因此在指令的定义中,我在范围内指定了变量“ binding”。
请参阅指令定义的代码:
app.directive('passwordRequirement',function()
{
return {
restrict: 'E',
scope:{binding:'@'},
templateUrl:'partials/content/common/passwordRequirement.html',
transclude:true
};
});
然后是用于密码要求的html模板(包含一个标签和一个复选框,供您选择是否取决于密码要求):
<div style="display:inline-block;">
<span data-ng-transclude></span>
<input type="checkbox" data-ng-disabled="true" data-ng-model="binding" data-ng-checked="binding">
{{binding}}
</div>
如您所见,我要将ng-model绑定到password.html中指定的变量。但是,如果我使用{{binding}}打印bind属性的值,它将打印正确的值。但是,如果我查看页面的源代码,则会看到:
<input type="checkbox" data-ng-disabled="true" data-ng-model="binding" data-ng-checked="binding" class="ng-pristine ng-valid" disabled="disabled" checked="checked">
这意味着在页面中的变量绑定没有被解释,因此无法正常工作。为什么?我无法执行data-ng-model = {{binding}},那么对此有什么解决方案?这在AngularJs中可行吗?如果是这样,实现该目标的正确方法是什么?我虽然是这样做的方式,但显然不是。
提前非常感谢您。
尝试在指令中使用双向绑定'='而不是文本绑定'@':
app.directive('passwordRequirement',function()
{
return {
restrict: 'E',
scope:{binding:'='},// here is the change
templateUrl:'partials/content/common/passwordRequirement.html',
transclude:true
};
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句