我刚刚开始探索AngularJS。我最近看过一个教程,解释如何设置基本过滤器。我现在正试图扩展这个概念。我觉得我接近这种方式的效率非常低。
此处使用的方法要求为每个新数据集设置新的Ctrl。如果您有5个不同的数据集要为其设置过滤器,则需要5个不同的控制器。当我看下面的例子时,我看到了许多重复的代码,这使得我可以做到不同的事情。
这是一个有效的jsfiddle:http://jsfiddle.net/smithd/eUZ7q/1/
<div ng-app="searchApp">
<div ng-controller="FilterCtrl" class="filter">
<h1>Search Demo</h1>
<hr/>
<div ng-switch on="selection">
<!-- <div ng-switch-default>default</div> -->
<div ng-switch-when="avengers">
<div ng-controller="AvengersCtrl">
<input type="text" ng-model="search">
<table ng-show="(filteredData = (avengers.cast | filter:search)) && search && search.length >= 1">
<tr ng-repeat="actor in avengers.cast | filter:search">
<td>{{actor.name}}</td>
<td>{{actor.character}}</td>
</tr>
</table>
</div>
</div>
<div ng-switch-when="expendables">
<div ng-controller="ExpendablesCtrl">
<input type="text" ng-model="search">
<table ng-show="(filteredData = (expendables.cast | filter:search)) && search && search.length >= 1">
<tr ng-repeat="actor in expendables.cast | filter:search">
<td>{{actor.name}}</td>
<td>{{actor.character}}</td>
</tr>
</table>
</div>
</div>
<select ng-model="selection" ng-options="item for item in items" class="filter"></select>
</div>
</div>
</div>
答案 0 :(得分:0)
以下是使用一个控制器处理所有内容并将数据存储在服务中的示例。
<div ng-controller="FilterCtrl">
<h1>Search Demo</h1>
<hr/>
<select ng-model="selection" ng-options="item for item in items" class="filter"></select> <hr/>
<div>
<input type="text" ng-model="search">
<table ng-show="(filteredData = (cast | filter:search)) && search && search.length >= 1">
<tr ng-repeat="actor in cast | filter:search">
<td>{{actor.name}}</td>
<td>{{actor.character}}</td>
</tr>
</table>
</div>
</div>
var app = angular.module('plunker', []);
app.factory('DataService', function () {
return { avengers: [...],expendables: [...]}
});
app.controller('FilterCtrl', function($scope,DataService){
$scope.items = ['avengers', 'expendables'];
$scope.selection = $scope.items[0];
/* change data when select changes*/
$scope.$watch('selection',function(){
$scope.cast=DataService[$scope.selection];
})
});
<强> Plunker demo 强>