I have an input field that is create by the following directive:
.directive('googlePlaces', function(){
return {
restrict:'E',
replace:true,
scope: {location:'='},
template: function (elem, attrs) {
return '<div><div class="form-group" ng-class="{ \'has-error\' : '+attrs.form+'.google_places_ac.$invalid }"><label>Address*</label><input id="google_places_ac" required name="google_places_ac" type="text" class="form-control" placeholder="Address" /><p class="help-block" ng-message="required" ng-show="'+attrs.form+'.google_places_ac.$invalid">Message</p></div></div>'
},
link: function($scope, elm, attrs){
var autocomplete = new google.maps.places.Autocomplete($("#google_places_ac")[0], {});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
$scope.location = place.name + ',' + place.geometry.location.lat() + ',' + place.geometry.location.lng() + "," + place.formatted_address;
$scope.$apply();
});
}
}
})
I have been trying exhaustively to add required validation to this field, but it doesn't work. I do the same for other input fields in my HTML form and it works fine.
This is the relevant HTML:
<form name="registrationForm" ng-submit="register()" novalidate>
...
<div class="col-xs-12">
<google-places location=location form="registrationForm"></google-places>
</div>
...
I've tried many different things, scope: {location:'=', form:'='}
, $compile
, just adding directly the name registrationForm
, or simply form
. None of it worked.
I would really appreciate if someone could help me with this :)
You could do this in many ways. Here are couple of them.
1) Isolate the validation and display of messages, accessing form etc from the
googlePlaces
directive and have the control of it given to the consumer as it really is a consumer's concern. They can have full control over how to display, what to display and where to display. This would avoid any more responsibilities to the directive who will just be responsible for providing the place selection. Have your directive require theng-model
and specify required attribute as well.So a rough implementation would be something like this.
and
2) You can 2 way bind the form object to the directive and control the validation and display message from there. You would need to place an
ng-model
on the input in order for validation to kick in properly.