AngularJS - 通过其他ng-repeat列表过滤ng-repeat列表

时间:2014-05-29 15:15:53

标签: angularjs angularjs-ng-repeat angularjs-filter

从这个fiddle开始,我试图通过其他ng-repeat列表生成的某个按钮来过滤ng-repeat列表。

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

  • $ scope.products => product.category_id
  • $ scope.categories => category.id

我在带有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}
];

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

但它无法正常工作:(我尝试在我的控制器中创建自定义过滤器,但我得到的结果相同。

提前感谢您的帮助:)

2 个答案:

答案 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)' />