samcooper11 samcooper11 - 6 months ago 21
Node.js Question

Update page after form submit - using Angular

I am using the MEAN framework - I have a basic form (as per below) that when data is entered it is sent to a rest API which then has a function that uses Mongoose to save data. That is all good... however i'm stuck on something more basic!

After a user has submitted this form it lands on a blank page with the api/img/add, how do i go back to my original page? I tried adding ng-submit="fetchImages()" within the form tag and then implementing a function in a script (also shown below) but for some reason this was not working, am i missing the point and doing something really wrong?

Thanks in advance

<form action="api/img/add" method="post" enctype="multipart/form-data">
<div>
<label for="image">Select an image</label>
<input type="file" name="image" id="image">
</div>
<div>
<label for="title">Title</label>
<input type="text" name="title" id="title">
</div>
<input type="submit">
</form>




< script >
angular.module('app', []).controller('main', ['$scope', '$http',
function($scope, $http) {
$scope.images = [];
$scope.fetchImages = function() {
$scope.images = [];
$http.get('api/img').then(function(res) {
$scope.images = JSON.parse(res.data);
}, function(res) {
console.log(res.statusText);
});
}

$scope.fetchImages();
}
]); < /script>




Answer

Try this: In html

    <form ng-submit="submitData()">
      <div>
        <label for="image">Select an image</label>
        <input type="file" ng-model="formdata.image" id="image">
      </div>
      <div>
        <label for="title">Title</label>
        <input type="text" ng-model="formdata.title" id="title">
      </div>
      <input type="submit">
    </form>

In your controller:

 angular.module('app', []).controller('main', ['$scope', '$http',
 function($scope, $http) {

   $scope.formdata = {};
   $scope.images = [];

   $scope.fetchImages = function() {
     $scope.images = [];
     $http.get('api/img').then(function(res) {
       $scope.images = JSON.parse(res.data);
     }, function(res) {
       console.log(res.statusText);
     });
   }

   $scope.fetchImages();

   //this function will post data to your api without refreshing the page
   $scope.submitData = function(){

      $http.post('api-comes-here', $scope.formdata).then(function(res) {
          //handle success
      }, function(error) {
           //handle error
      });


   }
 }
Comments