正确使用ng-submit

时间:2015-10-30 14:37:12

标签: javascript angularjs forms angularjs-ng-click ng-submit

我有一个表单向Google的地理编码器提交位置并返回纬度/经度并更改地图。如果我使用ng-点击图标它不起作用,除非我点击它两次。如果我在表单上使用ng-submit,它会附加到URL并且不执行任务。我觉得我已经接近让这个工作了,但我对自己做错了什么感到迷茫。

以下是表格

<li>
  <form action="" class="search-form" ng-submit="convertLatLonToAddress()">
      <div class="form-group has-feedback">
      <label for="search" class="sr-only">Search</label>
      <input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name">
          <i class="fa fa-search form-control-indicator"></i>                        
    </div>
  </form>
</li> 

这是函数

$scope.convertLatLonToAddress = function(){
  var address = $('#search').val();
  var geocoder = new google.maps.Geocoder();

  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var latitude = results[0].geometry.location.lat();
      var longitude = results[0].geometry.location.lng();
      // console.log(latitude + ' and ' + longitude);
      $scope.center.lat = latitude;
      $scope.center.lon = longitude;
    } 
  }); 
};

感谢@PSL,它已修复!见下文:

<li>
  <form class="search-form" ng-submit="convertLatLonToAddress(searchText)">
    <div class="form-group has-feedback">
      <label for="search" class="sr-only">Search</label>
      <input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name" ng-model="searchText">
      <button style="visibility: hidden"></button>
        <a ng-click="convertLatLonToAddress(searchText)">
          <i class="fa fa-search form-control-indicator"></i>                        
        </a>
    </div>
  </form>
</li> 

并且

$scope.convertLatLonToAddress = function(searchText){
  // var address = $('#search').val();
  var address = searchText;
  var geocoder = new google.maps.Geocoder();

  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var latitude = results[0].geometry.location.lat();
      var longitude = results[0].geometry.location.lng();
      // console.log(latitude + ' and ' + longitude);
      $scope.center.lat = latitude;
      $scope.center.lon = longitude;
      $scope.$apply();
    } 
  }); 
};

2 个答案:

答案 0 :(得分:2)

您需要在geocode的异步调用中手动调用摘要周期,因为geocode不会在角度上下文中运行。

geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var latitude = results[0].geometry.location.lat();
      var longitude = results[0].geometry.location.lng();
      // console.log(latitude + ' and ' + longitude);
      $scope.center.lat = latitude;
      $scope.center.lon = longitude;
      $scope.$apply();
    } 
  }); 

每次点击时,ng-click都会触发摘要周期,因此上一个周期会运行非角度异步调用和更新范围,而角度不知道,当您再次点击它时,它会再次运行摘要周期并执行相同但是那个时候你选择的值会被选中,这就是为什么需要2次点击。要使ng-submit执行,您需要一个表单元素触发器,例如:buttoninput type="submit"会导致表单上发生提交行为。除非您真的打算进行重定向,否则还应从表单中删除action

除此之外,您可以在文本框中使用ng-model并将值传递给您的函数,而不是直接从DOM获取值。

<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name" ng-model="searchText">

并将ng-click作为ng-click="convertLatLonToAddress(searchText)"传递给您,并在您的函数中使用它。

为了避免控制器中的scope.apply();,您可以将geoCoder抽象为角度服务并返回一个promise(创建延迟对象)并在控制器中使用该服务。

myApp.service('geoCoderService', ['$q', function($q){
      this.getCoordinates = function(address){
          var defer = $q.defer();
           var geocoder = new google.maps.Geocoder();

          geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             var latitude = results[0].geometry.location.lat();
             var longitude = results[0].geometry.location.lng();
             return defer.resolve({latitude :latitude , longitude :longitude });
           } 
          //faliure
          defer.reject(status);
       }); 
          return defer.promise;
      }

});

注入geoCoderService并使用以下方式获取数据:

 geoCoderService.getCoordinates(address).then(function(coordinates){
     //populate it
 }).catch(function(errorStatus){  /*ooops Error*/ })

答案 1 :(得分:0)

试试这个

&#13;
&#13;
 var app = angular.module('myApp', []);
 app.controller('myCtrl', function($scope) {
   $scope.convertLatLonToAddress = function() {
     var address = $('#search').val();
     var geocoder = new google.maps.Geocoder();
     geocoder.geocode({
       'address': address
     }, function(results, status) {
       if (status == google.maps.GeocoderStatus.OK) {
         $scope.lat = results[0].geometry.location.lat();
          $scope.lon = results[0].geometry.location.lng();
         console.log($scope.lat + ' and ' + $scope.lon);
         setTimeout(function(){$scope.$apply();},0)
       }
     });
   };
 });
&#13;
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <li>
      <div class="form-group has-feedback">
        <label for="search" class="sr-only">Search</label>
        <input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name">
        <i class="fa fa-search form-control-indicator"></i> 
        <button ng-click="convertLatLonToAddress()">Click</button>
        <br>
       Lat :  <input type="text" ng-model="lat"><br>
       Lon :  <input type="text" ng-model="lon">
        
      </div>
    </li>
  </div>
</body>
&#13;
&#13;
&#13;