【问题标题】:Thinkster MEAN stack tutorial, deletion of elementThinkster MEAN栈教程,删除元素
【发布时间】:2016-03-04 06:30:17
【问题描述】:

我一直在关注 Thinkster Mean Stack 教程,它非常有效。所以我创建了自己的项目,到目前为止一切正常。 但是,他们没有说明如何删除帖子。 而且我可以一辈子不知道如何从数据中删除一个元素。

AngularApp.js

var app = angular.module('KOL', ['ui.router'])
    .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('home', {
                url: '/home',
                templateUrl: "/views/home.ejs",
                controller: 'kolCtrl',
                resolve: {
                        patientPromise: ['patients', function(patients) {
                            return patients.getAll();
                        }]
                    }
            })
            .state('details', {
                url: '/details/{id}',
                templateUrl: './views/details.html',
                controller: 'detailsCtrl'
            });

            $urlRouterProvider.otherwise('home');
    }])
    .factory('patients', ['$http', function($http){
        var object = {
        patients: []               

       };

        object.getAll = function() {
            return $http.get('/patients').success(function(data) {
                angular.copy(data, object.patients);
            });
        }

        object.create = function(patient) {
        return $http.post('/patients', patient).success(function(data){
            object.patients.push(data);
        });
    }


    };
        return object;
    }])
    .controller('kolCtrl', ['$scope', 'patients', 
        function($scope, patients){

              $scope.patients = patients.patients;
              $scope.selectedItem = $scope.patients[0];


              $scope.addPost = function() {
                if(!$scope.title || $scope.title === '') { return; }
                if(!$scope.age || $scope.age === '') { return; }
                patients.create({
                    name: $scope.title,
                    age: $scope.age,
                })

                $scope.title = '';
                $scope.age = '';

              };



              object.delete = function(patient)            

    }])
    .controller('detailsCtrl', [
        '$scope',
        '$stateParams',
        'patients',
        function($scope, $stateParams, patients){


        $scope.patient = patients.patients[$stateParams.id];
    }])


;

Home.ejs

<div class="container">
        <div clas="row">

            <div style="width: 200px; margin-top: 100px">
            <select  ng-model="selectedItem" ng-options="patients.name for patients in patients" class="pull-left form-control" name="Vælg"></select>
            </div>
            <div class="viewbox pull-right">
                <h3>Patient: {{selectedItem.name}}</h3>
                <p>Age: {{selectedItem.age}} </p>
                <p>index: {{patients.indexOf(selectedItem)}}</p>
                <button><a href="#/details/{{patients.indexOf(selectedItem)}}">Rediger</a></button>
                <button ng-click="deleteItem(patients.indexOf(selectedItem))">Delete</button>
            </div>





        </div>
        <div class="row" class="pull-left">
            <div style="width: 200px; margin-top: 100px">
            <form  role="form" class="form-group" ng-submit="addPost()">
                <input  class="form-control" type="text" ng-model="title" />
                <input  class="form-control" type="text" ng-model="age" />
                <button type="submit">Add</button>
            </form>
            </form>
        </div>
     </div>
     </div>

index.js(路由获取和发布)

var express = require('express');
var router = express.Router();



/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

var mongoose = require('mongoose');
var Patient = mongoose.model('Patient');

router.get('/patients', function(req, res, next) {
  Patient.find(function(err, patients){
    if(err){ return next(err); }

    res.json(patients);
  });
});

router.post('/patients', function(req, res, next) {
  var patient = new Patient(req.body);

  patient.save(function(err, post){
    if(err){ return next(err); }

    res.json(patient);
  });
});

router.delete('/patients/:patient', function(req, res, next) {
    req.patient.remove(function(err, patient){
      if (err) { return next(err); }
      res.json(patient);
    });
});

router.param('patient', function(req, res, next, id) {
  var query = Patient.findById(id);

  query.exec(function (err, patient){
    if (err) { return next(err); }
    if (!post) { return next(new Error('can\'t find patient')); }

    req.patient = patient;
    return next();
  });
});

router.get('/details/:patient', function(req, res) {
  res.json(req.patient);
});

module.exports = router;

鉴于其他代码,我怀疑答案非常简单,但也许不是? 谢谢。

【问题讨论】:

  • 你能告诉我们处理你的请求的js文件吗?你已经发布了 angularjs 文件,但向我们展示了 node.js/express.js 文件,它应该有你的 get 和 post 函数。
  • 感谢您的回答。我进行了编辑,因此它现在包含 index.js,其中包含路由。这有帮助吗?

标签: angularjs json mean-stack


【解决方案1】:

根据您在index.js 文件中传递给router.delete 的函数:

router.delete('/patients/:patient', function(req, res, next) {
    req.patient.remove(function(err, patient){
      if (err) { return next(err); }
      res.json(patient);
    });
});

将delete 动词与$http 服务一起使用时,您必须将patients.id 附加到url。因此,您可以向患者工厂中的对象添加 delete 方法:

.factory('patients', ['$http', function($http){
    var object = {
    patients: []               

   };

    object.getAll = function() {
        return $http.get('/patients').success(function(data) {
            angular.copy(data, object.patients);
        });
    }

    object.create = function(patient) {
    return $http.post('/patients', patient).success(function(data){
        object.patients.push(data);
    });
    }

    //add patient id to the url
    object.delete = function(patient) {
    return $http.delete('/patients/',patient).success(function(data){
        console.log(data);
    });
    }
}


};
    return object;
}])

【讨论】:

  • 它说我不能做一个功能(患者.id)(意外令牌)
  • 好吧,它现在说:object.delete = function(patient.id),但是当我刷新页面时它会在 console.log 中抛出一个错误(Unexpected token . on line 40)第 40 行是 object.delete = function(patient.id)。这可能是对的吗?
  • 我认为部分问题是元素的索引(mongodb _id)没有从 ng-click 传递到控制器
  • 我想我需要解决方案的最后一部分。我需要 home.ejs ng-click 中的特定患者传递到 $scope.deletePatient。我该怎么做?我希望这不是太麻烦,我真的很感激。
  • 您能否正确创建和使用您的帖子功能?如果是这样的话?将 selectedItem 传递给 post 时使用相同的逻辑。如果您需要进一步的帮助,请尝试一些事情,然后用您需要帮助的具体内容更新问题。一旦您可以单击按钮并获取一名患者,您就可以将该患者传递给删除方法。
【解决方案2】:
 object.delete = function(patient) {
        return $http.delete('/patients', patient).success(function(data){
            for(var i = 0; i < object.patients.length; i++) {
                if(object.patients[i].id == patient.id) {
                    object.patients.splice(i, 1);
                }
        });

可能是这样的,在不知道回应的情况下很难说。如果响应(数据)是已删除的患者,那么您可以改用“if(object.patients[i].id == data.id)”

【讨论】:

  • 我上传了响应数据。这更有意义吗? :) 谢谢回答。还尝试使用您发布的内容。我会告诉你的!
猜你喜欢
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多