2014-10-08 81 views
0

我想回答我自己的未答覆question,但卡住了我無法弄清的一些奇怪的代碼結果。AngularJS動態表和ng-repeat

當我通過輸入普通高度和樓層號碼生成整個表格,然後逐個添加電梯時,該程序工作正常並且完美。

但是,當我通過點擊箭頭標誌手動添加一些行,然後添加電梯,而不是增加一個電梯它增加了許多電梯,其中電梯數量=手動添加的樓層數量。

我試着逐行查看代碼,但是我弄不明白,這裏的錯誤在哪裏。請支持!

我擔心的是在下面的功能主要是$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

在你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 

}); 

};