表单提交之后更新页面 – 使用Angular

我正在使用MEAN框架 – 我有一个基本的forms(如下所示),当input数据时,它被发送到一个其余的API,然后有一个函数,使用Mongoose来保存数据。 这一切都很好…但是我被卡住了更基本的东西!

在用户提交了这个表单后,它会在api / img / add的空白页面上出现,我该如何回到原来的页面? 我尝试在表单标签中添加ng-submit =“fetchImages()”,然后在脚本中实现一个函数(下面也显示),但由于某种原因,这是行不通的,我错过了点,做错了什么?

提前致谢

<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> 

试试这个:在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> 

在你的控制器中:

  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 }); } } 

如果你真的想回到最后一页,你可以使用:

 $window.history.back(); 

在你的例子中,我将在控制器中创build如下所示的函数,然后进行更改

 <input type="submit"> 

 <input type="submit" ng-click="goHome()"> 

我在这里用一个button来创build一个简单的plunk:

https://plnkr.co/edit/wzMlPF9kOmrGg01mOnBB?p=preview

JS

 app.controller('ctrl',function($scope,$window){ $scope.goHome = function() { $window.history.back(); } }); 

HTML

 <button ng-click="goHome()">Go Home</button>