2012-08-27 8 views
5

chcę serializować dane formularzy w angularjs. Poniżej znajduje się kod kontrolera:angularjs serialize dane formularza

function SearchCtrl($scope, $element, $http) { 
     $scope.url = 'php/search.php'; 
     $scope.submit = function() { 
      var elem = angular.element($element); 
      //var dt = $(elem.parent()).serialize(); 
      console.log($(elem.parent()).serialize()); 
      $http({ 
       method: 'POST', 
       url: $scope.url, 
       data: 'first=hgf&last=ghfgh', 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
      }).success(function(data, status) { 
       $scope.status = status; 
       $scope.data = data; 
       $scope.result = data; // Show result from server in our <pre></pre> element 
       //var elem = angular.element(e.srcElement); 
       //alert($(elem.parent()).serialize()); 
      }).error(function(data, status) { 
       $scope.data = data || "Request failed"; 
       $scope.status = status; 
      }); 
      return false; 
     }; 
} 

edycja:

<!DOCTYPE html> 
<html ng-app> 
<head> 
<title>Search form with AngualrJS</title> 
     <script src="../angular-1.0.1.min.js"></script> 
     <script src="http://code.jquery.com/jquery.min.js"></script> 
     <script src="js/search.js"></script> 



</head> 
<body> 
     <div> 
     <form ng-controller="SearchCtrl" ng-submit="submit()"> 
      <label>Search:</label> 
      <input type="text" ng-model="keywords" placeholder="enter name..."> 
      <input type="text" ng-model="desc" placeholder="enter description..."> 
      <button type="submit">Search</button> 
      <p>Try for example: "php" or "angularjs" or "asdfg"</p> 
     </form> 
<pre ng-model="result"> 
{{result}} 
</pre> 
    </div> 
</body> 

</html> 

ale nic nie pobiera drukowane na konsoli. gdzie ja idę źle?

+0

edytować treść zawierać html. – z22

+0

Zastanawiam się, dlaczego '$ (elem.parent()). Serialize())' jest używane zamiast tylko '$ (elem) .serialize()'. Czy to nie element $ tutaj ''

'jeden? – raina77ow

+0

Próbowałem z $ (elem) .serialize(), nadal nie wynik! co robię? – z22

Odpowiedz

8

Z doc:

Dla wartości elementu formularza, który ma być zawarty w odcinkach łańcucha, element musi mieć atrybut name.

W wejściach HTML nie ma nazw, dlatego serialize zwraca pusty ciąg znaków. Naprawić coś podobnego ...

<input type="text" name="keywords" ng-model="keywords" placeholder="enter name..."> 
<input type="text" name="desc" ng-model="desc" placeholder="enter description..."> 

I, przy okazji, nie trzeba zawijać kątowa $element do funkcji jQuery: $element.serialize() będzie działać OK.

Demo.

+0

$ element.serialize() nie działa sam, daje mi obiekt [[obiekt HTMLFormElement]] nie ma błędu "serializacji" metody w konsoli chrome – z22