在google places指令中使用AngularJS表单验证 [英] AngularJS form validation inside google places directive

查看:141
本文介绍了在google places指令中使用AngularJS表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  .directive('googlePlaces',function() {
return {
restrict:'E',
replace:true,
scope:{location:'='},
template:function(elem,attrs ){
return'< div>< div class =form-groupng-class ={\'has-error \':'+ attrs.form +'。google_places_ac。$ invalid} >< label> Address *< / label>< input id =google_places_acrequired name =google_places_actype =textclass =form-controlplaceholder =Address/>< p class =help-blockng-message =requiredng-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],{ });
goo gle.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();
});


})

我一直在努力尝试为此字段添加必需的验证,但不起作用。我为我的HTML表单中的其他输入字段做了同样的事情,它工作正常。



这是相关的HTML:

 < form name =registrationFormng-submit =register()novalidate> 
...
< div class =col-xs-12>
< google-places location = location form =registrationForm>< / google-places>
< / div>
...

我尝试了很多不同的东西,范围:{location:'=',form:'='} $ compile ,直接添加名称 registrationForm ,或简单地 form



如果有人可以帮我解决这个问题,我真的很感激:)

解决方案

你可以用很多方式来做到这一点。 1)隔离验证和显示消息,从 googlePlaces 中访问表单等。 指令并将其控制给予消费者,因为它确实是消费者的顾虑。他们可以完全控制如何显示,显示内容和显示位置。这样可以避免对负责提供地点选择的指令承担更多的责任。让你的指令需要 ng-model 并指定必需的属性。



所以粗略的实现就是这样。

 。 ('googlePlaces',function(){
return {
require:'ngModel',
restrict:'E',
replace:true,
scope: {
location:'= ngModel'
},
template:function(elem,attrs){
return'< div>< div class =form-group >< label> Address *< / label>< input id =google_places_acrequired name =google_places_actype =textng-model =locSearchclass =form-controlplaceholder =Address />< / div>< button type =buttonng-click =clear()>清除< / button>< / div>'
},
link :函数($ scope,elm,attrs,ctrl){
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();
});

$ scope.clear = function(){
$ scope.location = null;
}
}
}
});

 < google-places name =locationng-model = location required 
ng-class ={'has-error':registrationForm.location。$ invalid}>
< / google-places>
< span class =help-block
ng-show =registrationForm.location。$ invalid>请指定位置< / span>

angular.module('app',[] ).directive('googlePlaces',function(){return {require:'ngModel',restrict:'E',replace:true,scope:{location:'= ngModel'},template:function(elem,attrs){返回'< div>< div class =form-group>< label> Address *< / label>< input id =google_places_acrequired name =google_places_actype =text model =locationclass =form-controlplaceholder =Address/>< / div>< button type =buttonng-click =clear()>清除< / button><< ($(#google_places_ac)[0],{}); google。 maps.event.addListener(自动完成,'place_changed',function(){ var place = autocomplete.getPlace(); $ scope.location = place.name +','+ place.geometry.location.lat()+','+ place.geometry.location.lng()+,+ place.formatted_address; $范围$适用()。 }); $ scope.clear = function(){$ scope.location = null; }}}});

.has-error input { border:2px solid red;} < script src = https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script><script src =https://ajax.googleapis.com/ ajax / libs / angularjs / 1.4.7 / angular.min.js>< / script>< script src =https://maps.googleapis.com/maps/api/js?libraries=places> ;< / script>< div ng-app =app> < form name =registrationFormng-submit =register()novalidate> < div class =col-xs-12> < google-places name =locationng-model = location required ng-class ={'has-error':registrationForm.location。$ invalid}>< / google-places> < span class =help-blockng-show =registrationForm.location。$ invalid>请指定位置< / span> < / DIV> < / form>< / div>

可以2种方式将表单对象绑定到指令,并从那里控制验证和显示消息。您需要在输入中放置一个 ng-model ,以便验证正确使用。



<$ p $ ($'
')限制:'E',
替换为:true,
范围:{code> .directive('googlePlaces',function(){
return {
location:'=',
form:'='
},
template:function(elem,attrs){
return'< div>< div class =form-groupng-class ={\'has-error \':form.google_places_ac。$ invalid}>< label> Address *< / label>< input ng- model =selectedLocationid =google_places_acrequired name =google_places_actype =textclass =form-controlplaceholder =Address/>< p class =help-blockng-message = requiredng-show =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();
});
}
}
});

angular.module('app',[] ).directive('googlePlaces',function(){return {restrict:'E',replace:true,scope:{location:'=',form:'='},template:function(elem,attrs){return '< div>< div class =form-groupng-class ={\'has-error \':form.google_places_ac。$ invalid}>< label> Address *<标签>< input ng-model =locationid =google_places_acrequired name =google_places_actype =textclass =form-controlplaceholder =Address/>< p class =help如果您的网站使用了以下功能,则可以使用以下功能:$ scope,elm -lng-message =requiredng-show =form.google_places_ac。$ invalid> Message< / p>< / div>< / div> ,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; $范围$适用()。 }); }}})

.has-error input {border: 2px solid red;}

< script src =https ://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js>< / script>< script src =https://ajax.googleapis.com/ajax/ libs / angularjs / 1.4.7 / angular.min.js>< / script>< script src =https://maps.googleapis.com/maps/api/js?libraries=places>< ; / script>< div ng-app =app> < form name =registrationFormng-submit =register()novalidate> < div class =col-xs-12> < google-places location = location form =registrationForm>< / google-places> < / DIV> < / form>< / div>

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 the ng-model and specify required attribute as well.

So a rough implementation would be something like this.

.directive('googlePlaces', function() {
  return {
    require:'ngModel',
    restrict: 'E',
    replace: true,
    scope: {
      location: '=ngModel'
    },
    template: function(elem, attrs) {
      return '<div><div class="form-group"><label>Address*</label><input id="google_places_ac" required name="google_places_ac" type="text" ng-model="locSearch" class="form-control" placeholder="Address" /></div><button type="button" ng-click="clear()">clear</button></div>'
    },
    link: function($scope, elm, attrs, ctrl) {
      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();
      });

      $scope.clear = function() {
        $scope.location = null;
      }
    }
  }
});

and

 <google-places name="location" ng-model=location required 
               ng-class="{ 'has-error' : registrationForm.location.$invalid }">
 </google-places>
 <span class="help-block" 
       ng-show="registrationForm.location.$invalid">Please specify location</span>

angular.module('app', []).directive('googlePlaces', function() {
  return {
    require:'ngModel',
    restrict: 'E',
    replace: true,
    scope: {
      location: '=ngModel'
    },
    template: function(elem, attrs) {
      return '<div><div class="form-group"><label>Address*</label><input id="google_places_ac" required name="google_places_ac" type="text" ng-model="location" class="form-control" placeholder="Address" /></div><button type="button" ng-click="clear()">clear</button></div>'
    },
    link: function($scope, elm, attrs, ctrl) {
      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();
      });

      $scope.clear = function() {
        $scope.location = null;
      }
    }
  }
});

.has-error input {
  border: 2px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div ng-app="app">
  <form name="registrationForm" ng-submit="register()" novalidate>
    <div class="col-xs-12">
    
      <google-places name="location" ng-model=location required ng-class="{ 'has-error' : registrationForm.location.$invalid }"></google-places>
      <span class="help-block" ng-show="registrationForm.location.$invalid">Please specify location</span>
    </div>
  </form>
</div>

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.

.directive('googlePlaces', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      location: '=',
      form:'='
    },
    template: function(elem, attrs) {
      return '<div><div class="form-group" ng-class="{ \'has-error\' :form.google_places_ac.$invalid }"><label>Address*</label><input ng-model="selectedLocation" 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="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();
      });
    }
  }
});

angular.module('app', []).directive('googlePlaces', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      location: '=',
      form: '='
    },
    template: function(elem, attrs) {
      return '<div><div class="form-group" ng-class="{ \'has-error\' :form.google_places_ac.$invalid }"><label>Address*</label><input ng-model="location" 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="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();
      });
    }
  }
})

.has-error input {
  border: 2px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div ng-app="app">
  <form name="registrationForm" ng-submit="register()" novalidate>
    <div class="col-xs-12">
      <google-places location=location form="registrationForm"></google-places>
    </div>
  </form>
</div>

这篇关于在google places指令中使用AngularJS表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆