ngRepeat:尝试从数据库中获取时的dupe

时间:2018-05-13 20:30:12

标签: angularjs node.js express mongoose mean-stack

无论我尝试什么,我都会不断得到上述错误。当我在courses.js文件中注释掉“fetchCourses()”时,错误停止。我猜这个错误是在http请求中的某个地方,但我无法弄明白。

以下是我的代码段。

courses.js(控制器)

    var app = angular.module("app");

app.controller('coursesCtrl', ['$scope', 'Courses', '$routeParams', function ($scope, Courses, $routeParams) {

    function fetchCourses() {
        Courses.getCourses({}).then(function (res) {
            $scope.courses = res.data;
        }, function (err) {
            console.log(err);
        });
    }

    fetchCourses();

    $scope.modal = {
        title: "Modal",
        btnText: "Ok",
        save: function () {
            if ($scope.modal.type == 'course_delete') {
                Courses.deleteCourse($scope.modal.req).then(function (res) {
                    if (res.status == 200) {
                        $scope.courses.splice($scope.modal.req.index, 1);
                        $("#course_modal").modal("hide");
                    }
                }, function (err) {
                    console.log(err);
                });
            } else if ($scope.modal.type == 'course_create') {
                Courses.createCourse($scope.modal.req).then(function (res) {
                    $scope.courses.unshift(res.data);
                    $("#course_modal").modal("hide");
                }, function (err) {
                    console.log(err);
                });
            } else if ($scope.modal.type == 'course_edit') {
                $scope.courses[$scope.modal.req.index] = $scope.modal.req.course;
                $("#course_modal").modal("hide");
                $scope.modal.req.course = null;
            }
        },
        type: "default",
        req: {},
    };

    $scope.createCourse = function () {
        $("#course_modal").modal("show");
        $scope.modal.title = "Create course";
        $scope.modal.btnText = "Create";
        $scope.modal.type = "course_create";
        $scope.modal.req = {};
    };

    $scope.editCourse = function (index) {
        $("#course_modal").modal("show");
        $scope.modal.title = "Edit course";
        $scope.modal.btnText = "Ok";
        $scope.modal.type = "course_edit";
        $scope.modal.req.index = index;
    };

    $scope.deleteCourse = function (index) {
        $("#course_modal").modal("show");
        $scope.modal.title = "Delete course";
        $scope.modal.btnText = "Yes";
        $scope.modal.type = "course_delete";
        $scope.modal.req.index = index;
    };


}]);

Route.js

var Students = require('../../models/students');
var Courses = require('../../models/courses');
var Departments = require('../../models/departments');
var Exams = require('../../models/exams');
var ObjectId = require('mongoose').Types.ObjectId;
var bodyParser = require('body-parser');



module.exports = function (app) {

  app.use(bodyParser.urlencoded({
    extended: true
  }));


  app.post('/getCourses', (req, res) => {
    Courses.find({}).exec(function (err, documents) {
      res.send(documents);
      console.log(documents);
    });
  });




  app.post('/createCourse', (req, res) => {
    var data = {
      coursesName: req.body.coursesName,
      coursesProfessor: req.body.coursesProfessor,
      coursesDepartment: req.body.coursesDepartment,
      coursesNumStudents: req.body.coursesNumStudents,
    };
    Courses.create(data, function (err, document) {
      if (err) return res.status(500).send({
        message: "Sorry! There was a problem creating a course."
      });
      res.send(document);
      console.log(document);
    });
  });
};

menu.js(又名标题)

var menu = angular.module("menu", []);


menu.controller('menuCtrl', ['$scope', '$location', function ($scope, $location) {

  /*
  if (notloggedin){
    window.location.replace("/");
  } 
  */


  $scope.logout = function () {
    window.location.replace("/");
  }

  $scope.url = $location.url();
  console.log($location.url());




}]);

menu.service('Courses', ['$http', function ($http) {

  var Headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
  }

  var transformReq = function (obj) {
    var str = [];
    for (var p in obj)
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
  }

  this.getCourses = function (req) {
    return $http({
      method: 'POST',
      url: '/getCourses',
      headers: Headers,
      transformRequest: transformReq,
      data: req
    });
  }

  this.createCourse = function (req) {
    return $http({
      method: 'POST',
      url: '/createCourse',
      headers: Headers,
      transformRequest: transformReq,
      data: req
    });
  }
}]);

和courses.html

<div class="wrapper">
    <div ng-include="'header/menu.html'"></div>
    <div class="main-panel">
        <nav class="navbar navbar-default">
            <div class="container-fluid">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar bar1"></span>
                        <span class="icon-bar bar2"></span>
                        <span class="icon-bar bar3"></span>
                    </button>
                    <a class="navbar-brand" href="#">Courses</a>
                </div>
            </div>
        </nav>



        <div class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="header">
                                <h4 class="title">Courses List</h4>
                                <p class="category">Here is a list of all courses</p>
                                <button class="btn btn-success" style="float:right" ng-click="createCourse()">Create Course</button>
                            </div>
                            <div class="content table-responsive table-full-width">
                                <table class="table table-striped">
                                    <thead>
                                        <th>Name</th>
                                        <th>Professor</th>
                                        <th>Department</th>
                                        <th>Num of Students</th>
                                        <th>#</th>
                                    </thead>
                                    <tbody>
                                        <tr ng-repeat="c in courses">
                                            <td>{{c.coursesName}}</td>
                                            <td>{{c.coursesProfessor}}</td>
                                            <td>{{c.coursesDepartment}}</td>
                                            <td>{{c.coursesNumStudents}}</td>
                                            <td>
                                                <a href="" ng-click="editCourse($index)">Edit
                                                </a> /
                                                <a href="" ng-click="deleteCourse($index)">Delete
                                                </a>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="course_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h5 class="modal-title" id="modalLabel">{{modal.title}}</h5>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col">
                        <form ng-if="modal.type == 'course_create' || modal.type == 'course_edit'">
                            <div class="form-group">
                                <label for="coursesName">Name</label>
                                <input type="text" class="form-control" ng-model="modal.req.course.coursesName" ng-disabled>
                            </div>
                            <div class="form-group">
                                <label for="coursesProfessor">Professor</label>
                                <input type="text" class="form-control" ng-model="modal.req.course.coursesProfessor" ng-disabled>
                            </div>
                            <div class="form-group">
                                <label for="coursesDepartment">Department</label>
                                <input type="text" class="form-control" ng-model="modal.req.course.coursesDepartment" ng-disabled>
                            </div>
                            <div class="form-group">
                                <label for="coursesNumStudents">Number of Students</label>
                                <input type="text" class="form-control" ng-model="modal.req.course.coursesNumStudents" ng-disabled>
                            </div>
                        </form>

                        <div ng-if="modal.type == 'course_delete'">
                            Are you sure you want to delete this course?
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-success" ng-click="modal.save()">{{modal.btnText}}</button>
            </div>
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

这意味着 $scope.courses 有一些重复的值。禁止重复键,因为AngularJS使用键将DOM节点与项目关联。

所以在这种情况下你可以使用$ index跟踪。所以重复的项目将被它的索引跟踪。

<tr ng-repeat="c in courses track by $index">{{value}}</tr>