I have created a unique directive and I am looking to incorporate the validators from an input field used within this directive template. Is there a way to expand ngModelCtrl validators with the input validators?
This is my custom directive implementation:
angular.module('myModule')
.directive('myUrl', function() {
return {
restrict: 'A',
require: ['ngModel', '^form'],
replace: true,
templateUrl: '/components/url/my-url.html',
scope: {},
link: function(scope, element, attrs, ctrls) {
var ngModelCtrl = ctrls[0];
var formCtrl = ctrls[1];
scope.formField = ngModelCtrl;
// Scope data vars
scope.url = '';
// Watchers
scope.$watch('url', function(newValue) {
ngModelCtrl.$setViewValue(newValue);
});
// Validators
var inputValidators = formCtrl['my-url'].$validators;
ngModelCtrl.$validators = angular.copy(inputValidators);
// Custom render
ngModelCtrl.$render = customRender;
function customRender() {
scope.url = ngModelCtrl.$viewValue;
}
}
}
});
This is how it looks in my view:
<div>
<label>My URL</label>\
<input type="url" name="my-url" placeholder="http://" ng-model="url">
<div ng-messages="formField.$error" ng-show="formField.$invalid">
<span ng-message="url">Invalid URL.</span>
</div>
</div>
If you want to see a live example of the issue I'm facing, check out this fiddle link: https://jsfiddle.net/bsmaniotto/gzLmy1op/
Thank you for your help.
UPDATE:
Upon further analysis, it appears that the challenge does not lie in binding the validators of the input[url]
to my custom directive's ngModelCtrl
validators. It seems that when an invalid input is entered in the input[url]
element, the $modelValue
is not being set. As a result, my custom directive treats it as if nothing has been entered.