我有多个radio
按钮,我想根据所选的radio
按钮过滤来自网络API的结果。
HTML
<div class="row">
<div class="small-8 medium-9 large-10 columns">
<ul class="no-bullet">
<li data-ng-repeat="course in courses">
<a href="#/CoursesWillStart/{{ course.ID }}">{{ course.CourseName }}</a>
</li>
</ul>
</div>
<div class="small-4 medium-3 large-2 columns">
<ul class="no-bullet">
<li>
<label><input type="radio" name="filterRadio" value="RadioAll" data-ng-model="filterRadio" /> All</label>
</li>
<li>
<label><input type="radio" name="filterRadio" value="RadioToday" data-ng-model="filterRadio" /> Today</label>
</li>
<li>
<label><input type="radio" name="filterRadio" value="RadioThisWeek" data-ng-model="filterRadio" /> This Week</label>
</li>
<li>
<label><input type="radio" name="filterRadio" value="RadioThisMonth" data-ng-model="filterRadio" /> This Month</label>
</li>
<li>
<label><input type="radio" name="filterRadio" value="RadioSpecificDate" data-ng-model="filterRadio" /> Specific Date
<input type="date" name="from" data-ng-model="from" data-ng-show="filterRadio == 'RadioSpecificDate'" />
<input type="date" name="to" data-ng-model="to" data-ng-show="filterRadio == 'RadioSpecificDate'" />
</label>
</li>
<li>
<button class="my-button" data-ng-click="filterCourses(filterRadio)">Search</button>
</li>
</ul>
</div>
</div>
Javascript (相关)
myApp.controller('CoursesWillStartCtrl', ['$scope', 'GetCoursesWillStart',
function ($scope, GetCoursesWillStart) {
$scope.filterRadio = 'RadioAll';
$scope.filterCourses = function (filterRadio) {
switch (filterRadio) {
case 'RadioToday':
$scope.courses = coursesStartToday();
break;
case 'RadioThisWeek':
$scope.courses = coursesThisWeek();
break;
case 'RadioThisMonth':
$scope.courses = coursesThisMonth();
break;
case 'RadioSpecificDate':
$scope.courses = coursesInSpecificDate($scope.from, $scope.to);
break;
default: //all
$scope.courses = GetCoursesWillStart.query();
break;
}
};
$scope.filterCourses($scope.filterRadio);
}
]);
这是我在Angular中的第一个Web应用程序,上面的代码正在运行,但我不想操纵$scope.courses
,因此用户不必在完成所有课程之后每次过滤,都不要过度使用网络API。
我想我应该制作一个自定义过滤器。我看到了这个tutorial,但我不知道如何满足我的要求。那么有人可以告诉我如何制作自定义过滤器 - 或者如果有更好的方法 - 进行过滤吗?
答案 0 :(得分:0)
我发现这非常有用link描述了有关过滤器的所有内容。我的问题是我无法从视图到过滤器读取值。
但Angular会照顾这个,就像这样
course in courses | filterByDate:filterRadio
现在我已将filterRadio
发送到过滤器函数作为参数
angular.module('myAppFilters', []).filter('filterByDate',
function () {
return function (courses, filterRadio) {
//Also, I removed the switch from controller and added it here
}
});
此外,我们可以从 view 发送多个参数,如下所示:
course in courses | filterByDate:filterRadio:from:to
Angular的一个重要功能是别名命名:
course in courses | filterByDate:filterRadio:from:to as coursesFiltered
现在我们可以像coursesFiltered.length