Reputation: 8939
I'm trying to make a generic form validatation indicator. If the form is valid, it displays saying that the form is valid, else it displays an error saying that the form isn't valid.
I'm using bookingForm.$valid
or SOMEFORM.$valid
- but the ng-show
isn't working. I think the connection between {{formValid}}
and the actual form model isn't right.
Here's my directive:
sharedServices.directive('formValid', function() {
return {
restrict: 'A',
scope: {
formValid: '@'
},
template: '<div class="alert alert-warning" ng-show="!{{formValid}}.$valid"><b>ATH!</b> Útfylling ekki í lagi</div>' +
'<div class="alert alert-success" ng-show="{{formValid}}.$valid"><b>OK!</b> Útfylling í lagi</div>',
link: function(scope, element, attrs) {
scope.formValid = attrs.formValid;
}
};
});
Here's my usage:
<div form-valid="bookingForm"></div>
<form name="bookingForm">...</form>
<div form-valid="contactForm"></div>
<form name="contactForm">...</form>
I want to pass the form name (model) into my directive's template and display accordingly whether $valid is true/false on the forms model. Do I need to compile the template or how can I accomplish this?
Here's a GIF showing that it doesn't work, bookingForm.$valid
is correct in the HTML, but always false in the directive's template.
Upvotes: 1
Views: 77
Reputation: 54514
Because ng-show
creates a new scope, you need access the form in the $parent
scope. It's a bit tricky in terms of the model assignment. You can use attrs.$observe
to assign the object instead of the value of $valid
.
Please try this code:
sharedServices.directive('formValid', function () {
return {
restrict: 'A',
scope: {
formValid: '@'
},
template: '<div class="alert alert-warning" ng-show="!formValid.$valid"><b>ATH!</b> Útfylling ekki í lagi</div>' +
'<div class="alert alert-success" ng-show="formValid.$valid"><b>OK!</b> Útfylling í lagi</div>',
link: function (scope, element, attrs) {
attrs.$observe('formValid', function () {
scope.formValid = scope.$parent[attrs.formValid];
});
}
};
});
Upvotes: 1