【发布时间】:2015-10-18 05:54:20
【问题描述】:
尝试使用 Angular js 中的自定义指令匹配密码。虽然我看过几个谷歌教程,但我无法让它工作。我创建了一个 Plunker,显示它在 plunker 上不起作用。
HTML:
<div class="form-group" ng-class="{ 'has-error': form.password.$invalid && !form.username.$pristine }">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="user.password" required ng-minlength="6" ng-maxlength="12"/>
</div>
<div class="form-group" ng-class="{ 'has-error': form.confirm-password.$invalid && !form.confirm-password.$pristine }">
<label for="confirm-password">Confirm Password</label>
<input type="password" name="confirm-password" id="confirm-password" class="form-control" ng-model="user.confirmpwd" required equal="{{user.password}}"/>
<span ng-show="user.confirmpwd.$error.equal" class="help-block">Password does not match above</span>
</div>
JAVASCRIPT:
app.directive('equal', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.equal;
console.log(viewValue + ':' + comparisonModel);
if(!viewValue || !comparisonModel){
// It's valid because we have nothing to compare against
ctrl.$setValidity('equal', true);
}
// It's valid if model is lower than the model we're comparing against
ctrl.$setValidity('equal', viewValue === comparisonModel );
return viewValue;
};
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
$attrs.$observe('equal', function(comparisonModel){
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}]);
问题似乎与自定义指令有关,它似乎没有正确绑定到 ngModel 项?我觉得我一定错过了一些简单的东西,我刚刚开始学习 AngularJS。
【问题讨论】:
标签: angularjs angularjs-directive angular-directive