2014-09-25 51 views
0

將角度手錶放置在多維陣列上證明存在問題

我有一個屏幕,用戶將看到兩個團隊(外部數組),每個團隊都有一個團隊表(內部數組)。他可以拖放球員來改變擊球順序。

根據玩家在陣列中的位置更新battingOrder。

下面的解決方案是一個警察出/短期,但它確實解決了我的直接絆腳石。

然而,更優選的解決方案將被理解。 以下代碼在我的控制器中。

$scope.$watch(
     "Teams[0].TeamSheet", 
     function (newValue, oldValue) { 
      for (var i = 0; i < newValue.length; i++) { 
       newValue[i].battingOrder = i + 1; 
      } 
     }, 
     true 
    ); 

    $scope.$watch(
     "Teams[1].TeamSheet", 
     function (newValue, oldValue) { 
      for (var i = 0; i < newValue.length; i++) { 
       newValue[i].battingOrder = i + 1; 
      } 
     }, 
     true 
    ); 

    $scope.Teams = [{ 
     TeamName: "South-Africa", 
     TeamSheet: [ 
     { 
      name: "A Peterson", 
      battingOrder: 1, 
      mode: "view" 
     }, 
     { 
      name: "Riley Rossouw", 
      battingOrder: 2, 
      mode: "view" 
     }, 
     { 
      name: "H Amla", 
      battingOrder: 3, 
      mode: "view" 
     }, 
     { 
      name: "F Du Plessis", 
      battingOrder: 4, 
      mode: "view" 
     }, 
     { 
      name: "AB De Villiers", 
      battingOrder: 5, 
      mode: "view" 
     } 
     ] 
    }, 

    { 
     TeamName: "Australia", 
     TeamSheet: [ 
     { 
      name: "D Warner", 
      battingOrder: 1, 
      mode: "view" 
     }, 
     { 
      name: "S Watson", 
      battingOrder: 2, 
      mode: "view" 
     }, 
     { 
      name: "M Clarke", 
      battingOrder: 3, 
      mode: "view" 
     }, 
     { 
      name: "C Rogers", 
      battingOrder: 4, 
      mode: "view" 
     }, 
     { 
      name: "S Smith", 
      battingOrder: 5, 
      mode: "view" 
     } 
     ] 
    }]; 
+0

使用'$範圍$ watchCollection'按照商務部https://docs.angularjs.org /api/ng/type/$rootScope.Scope – Beyers 2014-09-25 14:24:00

回答

0

,你可以嘗試更新直接在視圖中擊球順序:

<div ng-repeat="member in team" ng-init="member.battingOrder = $index"> 
</div> 

那麼你就需要使用$看

編輯

以前的解決方案在您交換數組中的項目後無法工作。使用下面的代碼來解決這個問題:

<body ng-controller="MainCtrl"> 
    <div ng-repeat="member in team"> 
     {{setIndex(member,$index)}} 
     {{member.name}},{{member.index}} 
    </div> 
    <button ng-click="swap()">swap first with last</button> 
    </body> 

控制器:

app.controller('MainCtrl', function($scope) { 
    $scope.team = [ { index: 0, name : 'first' }, { index: 0, name : 'second' }, { index: 0, name : 'third' } ]; 
    $scope.swap = function() { 
    var tmp = $scope.team[0]; 
    $scope.team[0] = $scope.team[2]; 
    $scope.team[2] = tmp; 
    } 

    $scope.setIndex = function (member, index) 
    { 
    member.index = index; 
    } 

}); 

http://plnkr.co/edit/V3ixkww7dxcx8uZ7f0hj?p=preview