从这个fiddle开始,我试图通过其他ng-repeat列表生成的某个按钮来过滤ng-repeat列表。
我有两个共享相同属性的列表:
我在带有ng-repeat的html中生成这些列表,我希望能够使用也通过ng-repeat生成的类别按钮来过滤产品列表。
$scope.categories = [
{name: 'Category 1', id: 1},
{name: 'Category 2', id: 2},
{name: 'Category 3', id: 3},
];
$scope.products = [
{name: 'Product 1', category_id: 1},
{name: 'Product 2', category_id: 2},
{name: 'Product 3', category_id: 2},
{name: 'Product 4', category_id: 3},
{name: 'Product 5', category_id: 3},
{name: 'Product 6', category_id: 3}
];
<div ng-app ng-controller='ctrl'>
<nav>
<ul>
<li ng-repeat='category in categories'>
<input type="button" value='{{ category.name }}'
ng-click='showcat = {category_id: {{ category.id }} }' />
</li>
</ul>
</nav>
<ul>
<li ng-repeat='product in products | filter:showcat'>{{ product.name }}</li>
</ul>
查看我的fiddle
但它无法正常工作:(我尝试在我的控制器中创建自定义过滤器,但我得到的结果相同。
提前感谢您的帮助:)
答案 0 :(得分:3)
试试这个
function ctrl($scope) {
$scope.categories = [
{name: 'Category 1', id: 1},
{name: 'Category 2', id: 2},
{name: 'Category 3', id: 3},
];
$scope.products = [
{name: 'Product 1', category_id: 1},
{name: 'Product 2', category_id: 2},
{name: 'Product 3', category_id: 2},
{name: 'Product 4', category_id: 3},
{name: 'Product 5', category_id: 3},
{name: 'Product 6', category_id: 3}
];
$scope.showcat = { };
$scope.setShowCat = function(id){
$scope.showcat = {category_id: id };
}
}
和html
<div ng-app ng-controller='ctrl'>
<nav>
<ul>
<li ng-repeat='category in categories'>
<input type="button" ng-click='setShowCat (category.id)' value='{{ category.name }}' />
</li>
</ul>
</nav>
<ul>
<li ng-repeat='product in products | filter:showcat'>{{ product.name }}</li>
</ul>
</div>
答案 1 :(得分:0)
这是因为ng-repeat
创建了自己的子范围,因此当您在showcat
内设置ng-repeat
时,就像您正在做的那样,它只是该范围的本地。创建$scope
函数:
$scope.setShowcat = function(id) {
$scope.showcat = {category_id : id};
}
然后致电:
<input type="button" value='{{ category.name }}' ng-click='setShowcat(category.id)' />