2016-10-10 1 views
0

내 응용 프로그램에서 선택된 체크 박스를 세는 데 어려움을 겪고 있습니다. 다른 스택 오버플로 질문을 따라했지만 아직 주사위를 따라하지 않으려 고 노력했습니다. 확인란을 세는 데 경험이 있다면 도움이 될 것입니다.AngularJS에서 선택된 체크 상자를 선택하십시오.

HTML :

<div class="row"> 
     <div class="col-md-12"> 
     <table id="document-table" st-table="documents" st-safe-src="yourDisplayedCollection" class="table"> 
     <div>Total checked: ({{selectedCounter}})</div> 
      <thead> 
      <tr> 
       <th> 
       <st-select-all all="yourDisplayedCollection"></st-select-all> 
       </th> 
      </tr> 
      </thead> 
      <tbody> 
      <tr ng-repeat="document in documents"> 
       <td><input type="checkbox" ng-model="document.isSelected"/></td> 
      </tr> 
      </tbody> 
     </table> 
     </div> 
    </div> 

컨트롤러 :/** @ngInject */기능

.controller ('DocumentsController'($ 범위, restData, DateFormat을, 문서) {

$scope.dateFormat = dateFormats.angularDateFilter; 
    $scope.documents = documents.resultBag[0].documentBag; 
    $scope.yourDisplayedCollection = [].concat(documents.resultBag[0].documentBag); 
    $scope.selectAll = function (selected) { 
     var documents = $scope.documents; 
     angular.forEach(documents, function (documents) { 
      documents.selected = selected; 
     }); 
     // Update the counter 
     if(selected){ 
      $scope.selectedCounter = documents.length; 
     } else { 
      $scope.selectedCounter = 0; 
     } 
    }; 

편집 : 상단에있는 확인란을 모두 선택했는데 그 이유는 테이블의 yourDisplayedCollection과 ng-model = "document.isSelected"를 가지고 있기 때문입니다.

+0

여러 문제가 ... 한'NG-repeat'의 인 아이 범위를 변경 볼 수 없습니다. 이 확인란을 각 문서의 속성에 연결할 수 있습니까? 또는 그들은 분리되어 있어야합니까? – charlietfl

+0

내 대답을 아래에서보십시오. 위의 예를 살펴보고 재실행하면보다 의미가 있습니다. – Ohjay44

+0

https://ngcoderscope.wordpress.com/2016/08/12/multi-checkbox-directive/이 지시문이 도움이되기를 바랍니다. –

답변

1

예상 결과를 올바르게 이해하고 있다면 몇 가지 사항을 다시 작성해야합니다.

먼저 (HTML) :

<tr ng-repeat="document in documents"> 
    //Bind your model directily to the selected property in your object (document) 
    <td><input type="checkbox" ng-model="document.selected"/></td> 
</tr> 

둘째 :

$scope.selectAll = function (selected) { 
    var documents = $scope.documents; 
    angular.forEach(documents, function (doc) { 
     if(doc.selected) 
      $scope.selectedCounter +=1; 
    }); 

}; 

이 당신에게 정확한 카운트 매번를 제공 할 것입니다. 함수 이름이 오해의 소지가 있지만. SelectAll은 문자 그대로 모두 선택해야 함을 의미합니다. 나에게 그것은 당신의 계산처럼 보입니다.

이 작업을 수행하려면
+0

내 게시물을 편집하여 모든 컨트롤러를 포함합니다. – jeremy

+0

위 코드는 여전히 작동합니다. – Ohjay44

0

가장 간단한 방법은 Array.prototype.filter()를 사용하여 필터링 된 배열의 길이를 사용하는 것입니다

<input type="checkbox" ng-model="document.selected"/> 

그리고 카운터

:

$scope.selectedCounter = $scope.documents.filter(function(item){ 
    return item.selected; 
}).length; 

하는 당신은 항상 사용의 황금 규칙을 깨는 것을 인식 할 필요가 ng-model의 개체

ng-repeat

는 자식 범위를 생성하고 자식 범위에 원시적를 사용할 때 부모 컨트롤러는

+0

내 코드에 넣기가 힘들다 ... ... ( – jeremy

+0

어떤 오류가 발생 했습니까? – charlietfl

+0

아무런 오류도 발생하지 않았습니다 ... 이상한 – jeremy

관련 문제