简体   繁体   中英

convert jquery form submission to angular

I'm trying to convert the following jquery into angular, but can't seem to get it to work.

// jquery
$('#formsubmit').click(function(ev){
  ev.preventDefault();
  $.ajax({
    url: "/url.json",
    type: "POST",
    data: {email: $("#emailinput").val()},
    dataType: "json",
    success: function(data){
        console.log(data);
    },
    error: function(data){
      console.log(data);
    }
  });
});

<!--html -->
<form action="/" method="post">
  <input type="text" id="emailinput" name="emailinput" />
  <input type="submit" id="formsubmit">
</form>

Here is my angular. I put most of the logic into a controller, I'm not really sure if it's the best approach. Would it be better to use a directive?

var app = angular.module("app", []);

app.controller('myCtrl', [
'$scope',
'$http',
function($scope, $http) {
  $scope.submitform = function() {
    $http({
      url: "/url.json",
      method: "POST",
      data: {email: $scope.email}
    }).success(function(data, status, headers, config) {
      $scope.data = data;
    }).error(function(data, status, headers, config) {
      $scope.status = status;
    });
  }
}]);

<!-- html -->
<div ng-controller="myCtrl">
  <form method="post" ng-submit="submitform()" novalidate>
    <input type="text" ng-model="email" required></input>
    <button type="button"></button>
  </form>
</div>

EDIT

Thanks for the help so far. I adjusted a few things, but still having problems. When I click the button nothing seems to happen. Here's what I have so far.

------html------

<!-- putting everything in emailDir directive -->
<emailDir>
  <input type="text" ng-model="email"></input>
  <button ng-click="send">submit</button>        
</emailDir>

------factory file-----

var emailUser = angular.module("emailUsers", []);

emailUser.factory("emailUsers", [ "$http", "$q", function($http, $q){
  var fetch = function(theEmail){
    $http.post('/url', {email: theEmail})
        .success(function(data, status, headers, config) {
        $scope.data = data;
        console.log("success", data);
        }).error(function(data, status, headers, config) {
        $scope.status = status;
        console.log("error", status);
    });
  }
  return {
    fetch: fetch,
  }
}]);

-----directive------

var emailSubscribe = angular.module("emailsubscribe", []);

emailSubscribe.directive('emailDir', [function() {
  return {
    restrict: 'E',
    replace: true,
    controller: ['$scope', '$filter', '$attrs', 'i18n', 'emailUsers',   function($scope, $filter, $attrs, i18n, emailUsers) {
    $scope.email; 
    $scope.response = [];
    // when the user clicks the button with the ng-click="send", 
    // I want this to call the factory "emailUsers" fetch function function
    $scope.send = function() {
        emailUsers.fetch($scope.email).then(function(responses) {
            $scope.response = responses;
        });
      }
    }]
  };
}]);

--------dependencies-------

  // app.js file
  var dependencies = ["emailUsers", "emailsubscribe"]

I guess your sever side pick up the email by a variable String. But when you transform to angular, you send the email capsulating in a json object of this format {name:value} . It is not a String.

If I were right, just modify to data: $scope.email , it would be fine.

Can you show more about your sever side implementation?

You should call $http service post function like so:

$http.post('/url.json', {email: $scope.email})
  .success(function(data, status, headers, config) {
      $scope.data = data;
  }).error(function(data, status, headers, config) {
      $scope.status = status;
  });

And the <button> should be type submit , preferably with some text.

<button type="submit">go</button>

You can make the whole form a directive and use myCtrl as that directive's controller. See AngularJS Directive documentation .

You are call on submit but not passing any values. so you need to pass the values to the scope.

var app = angular.module("app", []);

app.controller('myCtrl', [
'$scope',
'$http',
function($scope, $http) {
  $scope.submitform = function(credentials) {
    $http({
      url: "/url.json",
      method: "POST",
      data: {email: credentials.email}
    }).success(function(data, status, headers, config) {
      $scope.data = data;
    }).error(function(data, status, headers, config) {
      $scope.status = status;
    });
  }
}]);

<!-- html -->
<div ng-controller="myCtrl">
  <form method="post" ng-submit="submitform(user)" novalidate>
    <input type="text" ng-model="user.email" required></input>
    <button type="submit"></button>
  </form>
</div>

I figured out what I was doing wrong. Directive names can't be camelcase in angular. Replace emailDir with emaildir

-----directive------

var emailSubscribe = angular.module("emailsubscribe", []);

emailSubscribe.directive('emaildir', [function() {
  return {
    restrict: 'E',
    replace: true,
    controller: ['$scope', '$filter', '$attrs', 'i18n', 'emailUsers',   function($scope, $filter, $attrs, i18n, emailUsers) {
    $scope.email; 
    $scope.response = []; 
  function
    $scope.send = function() {
        emailUsers.fetch($scope.email).then(function(responses) {
            $scope.response = responses;
        });
      }
    }]
  };
}]);

<emaildir>
  <input type="text" ng-model="email"></input>
  <button ng-click="send">submit</button>        
</emaildir>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM