简体   繁体   中英

AngularJS - function never called with ng-submit

I've created an angular-promise which calls a http method (corresponding to a rest service),which is supposed to be called when a form is submitted, using ng-submit. It never happens, and there is no error, it seems like the function is never called. So here is the javascript code:

myapp.factory('CardFactory', ['$http', function($http){
return{
    cardService: function(hclass) {
        return $http({
            method: 'get',
            url: UrlServices.baseUrl + 'http://localhost:8080//HSRestServices/hsrest/decks/getCards/' + hclass,
        })
    }
    }
  }])
myapp.controller('CardCtrl', ['$scope',  'CardFactory', function($scope, CardFactory ){

$scope.card = "Druid";

$scope.cardService = function() {


    CardFactory.cardService($scope.card)
        .then(function (response) {

            $scope.status = response.status;
            $scope.card = response.data;

            console.log("Response: " + JSON.stringify({data: response.data}));

            if (response.status == 200){
                $scope.card = response.data;
            } else {
                console.log("Response: Something went wrong.");
            }
        }, function (response) {
            console.log("Response: Something went wrong.");
        })
};
 }]);

and the html code:

<body ng-app="mainApp">
<div ng-controller="CardCtrl">
<form ng-submit="cardService()">
    <input type="submit" value="Submit">
</form>
<p ng-model="card">{{card}}</p>

  </div>

 </body>

Any ideas?Thank you in advance.

You have to give a name attribute to your form and all its subsequent form elements should have a name themselves too.

Also, you cannot have ng-model on a p tag. Use an input type text as follows:

HTML:

<form name="cardForm" ng-submit="cardService()" novalidate>
    <input type="text" name="card" />
    <input ng-model="card" type="submit" value="Submit">
</form>

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