好吧,我试图按区域过滤书籍。到目前为止,我可以从BD获取值,但UI不会更新。
HTML
<div class="col-lg-12" id="filter">
<div class="row">
<div class="col-lg-12" id="filter-title">
<h3>Filters:</h3>
</div>
<div class="col-lg-2 col-md-2 col-sm-3 col-xs-4 filters" ng-repeat="area in areas">
<div class="checkbox">
<input type="checkbox" checkbox-group> {{area.desc}}
</div>
</div>
</div>
</div>
角
app.controller('myBooks', function($scope,$http){
$scope.books = [];
$scope.limit = 30;
$scope.pagination = 0;
$scope.array = [];
// Search
$http.get('config/all').success(function(data){
if (data != 0) {
$scope.books = data;
}
else {
$scope.books = '';
}
// Number of pages
$scope.pages = function(){
return Math.ceil($scope.books.length / $scope.limit);
}
});
// Search area
$http.get('areas').success(function(areas){
$scope.areas = areas;
});
})
指令
.directive("checkboxGroup", function ($http) {
return {
restrict: "A",
link: function (scope, elem, attrs) {
elem.bind('click', function () {
scope.$apply(function () {
var index = scope.array.indexOf(scope.area.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.area.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
$http.post('config/booksAreas', {"area" : scope.array}).success(function(data){
scope.books = data;
scope.pages = function(){
return Math.ceil(scope.books.length / scope.limite);
}
});
});
});
}
}
JsFiddle中的相同示例,但没有ajax:http://jsfiddle.net/W295L/
答案 0 :(得分:1)
我用自定义过滤器做到了:
<input type="checkbox" data-ng-click="setSelected(area.id)" /> <!-- you can do this also with some button and style it with css if selected -->
和你的书单
<ul>
<li ng-repeat="book in books | bookFilter:array">{{book.name}}</li>
</ul>
在控制器中添加以下方法:
$scope.setSelected = function (id) {
var idx = $scope.array.indexOf(id);
if (idx > -1) {
$scope.array.splice(idx, 1);
} else {
$scope.array.push(id);
}
console.log($scope.array);
return false;
};
通过以下方式替换您的指令:
.filter('bookFilter', [function () {
return function (books, selectedArea) {
if (!angular.isUndefined(books) && !angular.isUndefined(selectedArea) && selectedArea.length > 0) {
var tempBooks = [];
angular.forEach(selectedArea, function (id) {
angular.forEach(books, function (book) {
if (angular.equals(book.area, id)) {
tempBooks.push(book);
}
});
});
return tempBooks;
} else {
return books;
}
};
}])
查看更新后的fiddle