我的工作链接多个过滤器,但同时认为它才意识到它创建的代码的极端量(redudancy将在此用例的最好的术语),这让我不知道这是否可以更动态地完成/推广。 基本上我有5-6下拉菜单,其中用户可以选择一个或多个选项,以将数据与过滤。 我做了这基于一个下拉菜单,但我想进一步扩大这一点。 在此代码示例我有基于一个柱中挑选出一个下拉菜单。
JavaScript的:
<script>
'use strict';
var App = angular.module('App',['ngResource','App.filters']);
App.controller('ExerciseCtrl', ['$scope','$http', function($scope, $http) {
$scope.selectedMainMuscle = [];
$http.get('/rest/exercises/')
.then(function(res){
$scope.exercises = res.data;
});
$scope.orderProp = 'name';
$http.get('/rest/muscles/')
.then(function(res){
$scope.muscles = res.data;
});
$scope.isChecked = function () {
if (_.contains($scope.selectedMainMuscle, this.muscle.id)) {
return 'glyphicon glyphicon-ok pull-right';
}
return false;
};
$scope.setSelectedMainMuscle = function () {
var id = this.muscle.id;
if (_.contains($scope.selectedMainMuscle, id)) {
$scope.selectedMainMuscle = _.without($scope.selectedMainMuscle, id);
} else {
$scope.selectedMainMuscle.push(id);
}
return false;
};
}]);
angular.module('App.filters', []).filter('mainMuscleFilter', [function () {
return function (exercises, selectedMainMuscle) {
if (!angular.isUndefined(exercises) && !angular.isUndefined(selectedMainMuscle) && selectedMainMuscle.length > 0) {
var tempClients = [];
angular.forEach(selectedMainMuscle, function (id) {
angular.forEach(exercises, function (exercise) {
if (angular.equals(exercise.main_muscle.id, id)) {
tempClients.push(exercise);
}
});
});
return tempClients;
} else {
return exercises;
}
};
}]);
</script>
HTML:
<div class="btn-group" ng-class="{open: dd2}">
<button type="button" class="btn btn-default dropdown-toggle" ng-click="dd2=!dd2">Main muscle <span class="caret"></span></button>
<ul class="dropdown-menu">
<li ng-repeat="muscle in muscles">
<a href ng-click="setSelectedMainMuscle()">{%verbatim%}{{muscle.name}}{%endverbatim%} <span data-ng-class="isChecked()"></span></a>
</li>
</ul>
</div>
<table class="table table-hover" >
<tr><td><strong>Name</strong></td><td><strong>Main muscle</strong></td><td><strong>Equipment</strong></td></tr>
<tr ng-repeat="exercise in filtered = (exercises | mainMuscleFilter:selectedMainMuscle)">
{%verbatim%}<td>{{exercise.name}}</td><td>{{exercise.main_muscle.name}}</td><td>{{exercise.equipment.name}}</td>{%endverbatim%}
</tr>
</table>