AngularJS - 通过另一个 ng-repeat 列表过滤 ng-repeat 列表

标签 angularjs angularjs-ng-repeat angularjs-filter

从此fiddle ,我正在尝试通过其他 ng-repeat 列表生成的某个按钮来过滤 ng-repeat 列表。

我有两个共享相同属性的列表:

  • $scope.products => 产品.category_id
  • $scope.categories => 类别.id

我使用 ng-repeat 在 html 中生成这些列表,并且我希望能够使用同样使用 ng-repeat 生成的类别按钮来过滤产品列表。

Controller

$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}
];

HTML

<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

但它不起作用:(我尝试在 Controller 中创建自定义过滤器,但得到了相同的结果。

预先感谢您的帮助:)

最佳答案

试试这个

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>

关于AngularJS - 通过另一个 ng-repeat 列表过滤 ng-repeat 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23936721/

相关文章:

javascript - 尝试了解 Angular 路由概念,但是当尝试重新加载页面时,没有显示任何内容。

javascript - Angular 复选框过滤器不留下任何数据

javascript - 访问状态响应

html - 如何将查询字符串附加到 Angular ui-router 中的 URL

javascript - 推送后 Angular ng-repeat 未更新

javascript - 添加额外的 btn-group onclick

javascript - 如何在同一个表中显示这两个嵌套 ng-repeats 中的元素

javascript - Angular 重复顺序不适用于嵌套范围

javascript - AngularJS ng-repeat 具有更好的性能 - 在 Controller 中重新分配值或过滤值

javascript - AngularJS - 检查 ng-if 的条件