2014-08-29 4 views
0

여러 개의 체크 박스를 필터링하고 싶지만 한 번에 하나씩 만 선택할 수 있습니다. 이 값을 구조화하는 방법을 모르므로 모든 값을 필터링 할 수 있습니다.angularjs 여러 체크 박스 필터링

fiddle을 만들었습니다. 도움을 주시면 감사하겠습니다. 그들은 모두 같은 모델 속성에 바인딩하기 때문에 지미

답변

1

동시에 체크 박스를 선택 할 수 없다는의 주된 문제

<input type="checkbox" id="cb" ng-model="word" ng-true-value="has kitchen" ng-false-value=""> 

이다.

이전에 언급 한 바와 같이 필터에 대해 다른 선언적 문제가 있지만 맞춤 필터를 만드는 것이 어쨌든 필요 이상으로 과장 될 수 있습니다.

$scope.options = [ 
    { 
    name: 'has kitchen', 
    selected: false 
    }, { 
    name: 'has bakery', 
    selected: false 
    }]; 

을하고 일을하기 위해 좀 더 명확 당신의 체크 박스

다음
<label ng-repeat="option in options"> 
    <input type="checkbox" ng-model="option.selected"/>{{option.name}} 
</label> 

을 구축 할 반복 :

내 접근 방식은 개별적으로 선택을 추적 옵션의 배열을 생성하는 것입니다 (불필요한 중첩을 피하면서) 작업 할 모델을 간단하게 만들 수 있습니다.

$scope.data = [{ 
    "name" : "one", 
    "services" : ["has bakery", "has dispensary"], 
    "address" : "21 regent st chippendale" 
    },{ 
    "name" : "two", 
    "services" : ["has bakery", "has dispensary", "has food hall", "has kitchen"], 
    "address" : "25 regent st chippendale" 
    },{ 
    "name" : "three", 
    "services" : ["has food hall", "has kitchen"], 
    "address" : "25 regent st chippendale" 
    }]; 

당신은 필터 기능이 다른 각 항목에 대해 한 번만 호출하고 해당 항목을 선택한 모든 옵션이있는 경우 true를 반환하고, 거짓됩니다

<ul> 
    <li ng-repeat="item in data | filter:itemFilter">{{item.name}}</li> 
</ul> 

필터링을 제공하기 위해 간단한 컨트롤러 기능을 사용할 수 있습니다.

$scope.itemFilter = function(item) { 
    var filters = $scope.options.filter(function(element, idx, array) { 
     return element.selected; 
    }) || []; 

    var matched = true; 
    filters.forEach(function(option) { 
     matched = matched && item.services.indexOf(option.name) >=0; 
    }) 
    return matched; 
    }; 

이 (제거 일반 특급 물건과) 일치하는 논리의 단순화 된 버전이지만,이 메커니즘을 설명해야하고 당신이 거기에서 경우 걸릴 수 있습니다 부여. 여기

여기에 원래 JSON 모델

<ul> 
    <li ng-repeat="item in data.list | filter:itemFilter">{{item.name}}</li> 
</ul> 

새로운 필터 기능 (정말 우아하지 작동해야 다른 버전의

작업 예를 http://plnkr.co/edit/nyBqQAHx8VgbNFICZMou

편집, 그러나 보인다 시도한 경우 작동)

$scope.itemFilter = function(item) { 
    var filters = $scope.options.filter(function(element, idx, array) { 
     return element.selected; 
    }) || []; 

    var matched = true; 
    filters.forEach(function(option) { 
     var matchingService = item.services[0].services.filter(function(element, idx, array) { 
     return element.serviceName == option.name; 
     }) || []; 
     matched = matched && matchingService.length > 0; 
    }); 

    return matched; 
    }; 

업데이트 된 예 http://plnkr.co/edit/Wlk5wQdXS7OZhSNxhqOA

+0

안녕하세요 @MPowerKC, 질문에 너무 간결하게 대답 해 주셔서 감사합니다. 전반적인 인프라 스트럭처의 일부로 JSON을 변경할 수는 없지만 시도해 볼 아이디어는 분명 있습니다. – Jimi

+0

@Jimi 원래 json 형식을 사용하는 위의 편집을 살펴보십시오. 희망이 도움이 :) – MPowerKC