2015-10-19 19 views
2

我目前在我的web應用程序中有一個複選框列表。我想顯示覆選框已被檢查的順序。所以我寫了下面的代碼。如何在AngularJS中註冊複選框的順序?

$scope.updateNumbers = function(id, checked, inputs) { 
    if (checked === true) { 
     $scope.count += 1; 
     var span = angular.element('#'+id+'-'+id); 
     span.html($scope.count); 
    } else { 
     if ($scope.count != 0) { 
      $scope.count -= 1; 
     } 

     for (index = 0; index < inputs.length; ++index) { 
      var input = inputs[index]; 

      var span = angular.element('#'+test.id+'-'+test.id); 
      if (span.html() > $scope.count || span.html() == $scope.count) { 
       span.html(span.html()-1); 
      } 
     } 

     var span = angular.element('#'+id+'-'+id); 
     span.html($scope.count); 
    } 
} 

而這個HTML

<div class="list-view__body__row" ng-repeat="restaurant in restaurants"> 
    <div class="list-view__body__cell"> 
     <input type="checkbox" id="<% restaurant.id %>" value="" 
      class="input-field__checkbox--input" 
      ng-model="restaurant.checked" 
      ng-change="updateNumbers(restaurant.id, restaurant.checked, restaurants)"> 
     <label for="<% restaurant.id %>" 
      class="input-field__checkbox--label" 
      ng-bind-html="restaurant.name|html"></label> 
    </div> 
    <div class="list-view__body__cell"> 
     <div class="order__wrapper" ng-show="restaurant.checked"> 
      <span id="<% restaurant.id %>-<% restaurant.id %>">0</span> 
     </div> 
    </div> 
</div> 

在目前的實現,不過,有時數量會下降到0或數字將出現兩次。它工作不正常,那麼我該如何改進這些代碼呢?

+2

應該不需要操作DOM自己做任何這一點。使用你的數據模型來驅動角度視圖 – charlietfl

+0

當你選中一個複選框時,如果你的對象中有一個數字字段,當你選中它時可以改變爲1並對其進行分類 –

回答

0

使用角度,您總是希望您的數據模型驅動視圖。請注意,以下解決方案不需要dom操作代碼,並根據數據角度管理dom。它也只需要很少的代碼。

您需要的全部內容都是數據模型中檢查過的餐廳數組。

然後,順序由該數組中的索引確定,count是數組的長度。

控制器:

// array to store selections 
    $scope.checkedItems=[]; 

    $scope.updateSelections = function(rest){   
    if(rest.checked){ 
     // add to array if item is checked 
     $scope.checkedItems.push(rest) 
    }else{ 
     // remove from array if not checked 
     $scope.checkedItems.splice($scope.checkedItems.indexOf(rest),1) 
    } 
    } 

查看:

<div ng-repeat="restaurant in restaurants"> 
    <div> 
     <input type="checkbox" ng-model="restaurant.checked" 
      ng-change="updateSelections(restaurant)"> 
     <label ng-bind="restaurant.name"></label> 
    </div>   
    <div ng-show="restaurant.checked"> 
     <!-- Use index to display order --> 
     Order: <span>{{checkedItems.indexOf(restaurant) +1}}</span> 
    </div>   
    </div> 

    <h3>Count of checked items: {{checkedItems.length}}</h3> 

DEMO