Angularjs 存储 $scope 变量

Angularjs storing $scope variable

我正在使用 Yeoman Angular-fullstack 构建网络应用程序。我对如何更新我的 $scope 变量感到困惑,以便在进行更改后,结果会自动显示在 html 页面上而无需刷新。

HTML

<h1 class="page-header">Drugs:</h1>
<div class="row">
    <div class="col-sm-4 col-sm-offset-4">
        <div ng-repeat="current in alldrugs">
                <p>
                <a href="/edit={{current._id}}"> <button class="btn btn-default" type="button">{{current.name}}</button></a>
                <a ng-click="delete(current)"><button class="btn btn-default" type="button">delete</button></a>
              </p>   
        </div>
    </div>
  </div> 

Controller.js

'use strict';

angular.module('firstApp')
  .controller('MainCtrl', function ($scope, $http) {
    $scope.alldrugs = [];

    $http.get('/api/drugs').success(function(alldrugs) {
      $scope.alldrugs = alldrugs;
    });

    $scope.delete = function(thing) {
      $http.delete('/api/drugs/' + thing._id);
      $http.get('/api/drugs').success(function(alldrugs) {
        $scope.alldrugs = alldrugs;
      });
    };
  });

当调用 $scope.delete 时,该项目被删除,但是在我刷新页面之前页面不会反映更改。我认为它与 http 回调函数的范围有关。如有任何帮助,我们将不胜感激。

问题是 $http.delete 和 $http.get 都是异步调用的。

调用$http.get时,$http.delete还没有完成。您必须确保在删除后调用 get。

这段代码可以工作,尽管它不是一个优雅的解决方案:

$scope.delete = function(thing) {
  $http.delete('/api/drugs/' + thing._id).success(function(){
        //The get will be called AFTER the delete
        $http.get('/api/drugs').success(function(alldrugs) {
           $scope.alldrugs = alldrugs;
        });
  });
};

您只需要一个请求就可以解决它:

 $scope.delete = function(thing) {
  $http.delete('/api/drugs/' + thing._id).success(function(){
      $scope.alldrugs = $scope.alldrugs.filter(function(t) {
          return t._id !== thing._id; // Remove the drug which was deleted 
      });
  })
  .error(function() {
       // Drug couldnt be deleted, notify the user?
  });
};