简体   繁体   English

http请求后Angular不更新页面(范围问题?)

[英]Angular not updating page after http request (scope issue?)

When my page loads, all the items in my mongo db are displayed.当我的页面加载时,我的 mongo db 中的所有项目都会显示出来。 I have a form to input new entries, or delete entries.我有一个输入新条目或删除条目的表单。 When creating or deleting, the http process works, but the new data is not updated in the DOM.创建或删除时,http 进程有效,但新数据不会在 DOM 中更新。

Most of the related questions I have researched suggest to make sure my ng-controller wraps the entire body, which it does.我研究过的大多数相关问题都建议确保我的 ng-controller 包裹了整个身体,它确实如此。 Other's suggest to use $apply, but I've also read that this is wrong.其他人建议使用 $apply,但我也读到这是错误的。 When I try it, I am alerted "in progress" anyway.当我尝试它时,无论如何我都会收到“正在进行中”的警报。

My only guess is that after the http request, a new scope is loaded and angular doesn't pick up on that.我唯一的猜测是,在 http 请求之后,加载了一个新的作用域,而 angular 不会对此进行处理。 Or for some reason its just not reloading the data after my request.或者出于某种原因,它只是在我请求后没有重新加载数据。 Here is my code, thanks for your help.这是我的代码,感谢您的帮助。

index.html索引.html

<body ng-controller="MainController">

    <!-- list records and delete checkbox -->
    <div id="record-list" class="row">
        <div class="col-sm-4 col-sm-offset-4">
            <!-- loop over records in $scope.records -->
            <div class="checkbox" ng-repeat="record in records">
                <label>
                    <input type="checkbox" ng-click="deleteRecord(record._id)">
                    {{ record.artist}} - {{ record.album }} - {{ record.bpm}}
                </label>
            </div>
        </div>
    </div>
    <!-- record form data -->
    <div id="record-form" class="row">
        <div class="col-sm-8 col-sm-offset-2 text-center">
            <form>
                <div class="form-group">
                    <input type="artist" class="form-control input-lg text-center" placeholder="Artist" ng-model="formData.artist">
                </div>
                <div class="form-group">
                    <input type="album" class="form-control input-lg text-center" placeholder="Album" ng-model="formData.album">
                </div>
                <div class="form-group">
                    <input type="bpm" class="form-control input-lg text-center" placeholder="BPM" ng-model="formData.bpm">
                </div>
                <button type="submit" class="btn btn-primary btn-lg" ng-click="createRecord()">Add</button>
            </form>
        </div>
    </div>
</div>

controller.js控制器.js

angular.module('myApp', []).controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.formData = {};
$scope.sortType     = 'artist';
$scope.sortReverse  = false;
//$scope.searchRecords   = '';
$http.get('/api/records/')
  .success(function(data) {
      $scope.records = data;
      console.log(data);
  })
  .error(function(data) {
      console.log('Error: ' + data);
  });
  $scope.createRecord = function() {
      $http.post('/api/records/', $scope.formData)
          .success(function(data) {
              //$scope.formData = {};
              $scope.records = data;
              console.log(data);
          })
          .error(function(data) {
              console.log('Error: ' + data);
          });
  };
  $scope.deleteRecord = function(id) {
      $http.delete('/api/records/' + id)
          .success(function(data) {
              $scope.records = data;
              console.log("delete record scope: " + data);
          })
          .error(function(data) {
              console.log('Error: ' + data);
          });
  };

}]) }])

Your controller JS looks fine - I would say from looking at this that you need to export the updated values from your mongoDB collection when the POST/DELETE is successful.您的控制器 JS 看起来不错 - 我会说,当 POST/DELETE 成功时,您需要从 mongoDB 集合中导出更新的值。

If you use Mongoose (mongoDB plugin), you can update your API code to send back the updated data upon success with something like this:如果您使用 Mongoose(mongoDB 插件),您可以更新您的 API 代码,以便在成功后发送更新的数据,如下所示:

// POST
// --------------------------------------------------------
// Provides method for saving new record to the db, then send back list of all records

app.post('/api/records', (req, res) => {

    // Creates a new record based on the Mongoose Schema
    const newRecord= new Record(req.body);

    // New record is saved to the db
    newRecord.save((err) => {

        // Test for errors
        if(err) res.send(err);

        // Now grab ALL data on records 
        const all = Records.find({});
        all.exec((err, records) => {

           // Test for errors
           if(err)  res.send(err);

           // If no errors are found, it responds with JSON for all records
           res.json(records);
        });

    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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