AngularJS动态表和ng-repeat

时间:2014-10-08 10:33:50

标签: angularjs angularjs-scope angularjs-ng-repeat

我正在尝试回答我自己未回复的问题question但是我的代码有些奇怪的结果,我无法弄清楚。

当我通过输入共同的高度和楼层数来生成整个表格然后逐个添加Elevators时,程序运行良好且完美。

但是当我通过点击箭头标志手动添加一些行然后添加电梯时,它增加了许多电梯而不是添加一个电梯,其中电梯的数量=手动添加的楼层数。

我试着逐行查看代码,但我无法弄清楚,这里的bug在哪里。请支持!

我担心的问题主要是$scope.AddElevator

$scope.AddElevator = function(ElevatorName) {

    console.log("Floor Numbers");
    console.log($scope.Floors.length);
   /* $scope.Floors.sort(function(a, b) {
      if (a.FloorNo > b.FloorNo) {
        return -1;
      }
      if (a.FloorNo < b.FloorNo) {
        return 1;
      }
      // a must be equal to b
      return 0;
    });
    */
    // CODE to ADD New Elevator in Table 
    for (var i = 0; i < $scope.Floors.length; i++) {
      console.log(i);
      $scope.Floors[i].LiftServeDetails.push({
        Name: ElevatorName,
        ASide: "Available",
        BSide: "N/A"

      });
      console.log($scope.Floors[i]);
    }
  };
 // Add Row on top of a Row
  $scope.floorUp = function(floorno) {
    $scope.tmpLiftServeDetails = [];
    $scope.tmpLiftServeDetails = $scope.Floors[0].LiftServeDetails;

    for (var i = 0; i < $scope.Floors.length; i++) {
      if ($scope.Floors[i].FloorNo > floorno) {
        $scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
      }
    }

    $scope.Floors.push({
      FloorNo: floorno + 1,
      Level: null,
      Height: 0,
      Shops: 0,
      LiftServeDetails: $scope.tmpLiftServeDetails

    });

  };

  // Add Row in bottom of a Row
  $scope.floorBottom = function(floorno) {
    $scope.tmpLiftServeDetails = [];
    $scope.tmpLiftServeDetails = $scope.Floors[0].LiftServeDetails;

    for (var i = 0; i < $scope.Floors.length; i++) {
      if ($scope.Floors[i].FloorNo >= floorno) {
        $scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
      }
    }
    $scope.Floors.push({
      FloorNo: floorno,
      Level: null,
      Height: 0,
      Shops: 0,
      LiftServeDetails: $scope.tmpLiftServeDetails
    });

  };

1 个答案:

答案 0 :(得分:1)

在您的floorUp和floorBottom函数中,您没有复制对象,而是引用它们。

试试这个:

$scope.floorUp = function(floorno) {
var tmpLiftServeDetails = angular.copy($scope.Floors[0].LiftServeDetails);

for (var i = 0; i < $scope.Floors.length; i++) {
  if ($scope.Floors[i].FloorNo > floorno) {
    $scope.Floors[i].FloorNo = $scope.Floors[i].FloorNo + 1;
  }
}

$scope.Floors.push({
  FloorNo: floorno + 1,
  Level: null,
  Height: 0,
  Shops: 0,
  LiftServeDetails: tmpLiftServeDetails

});

};