【问题标题】:Why is angular not clearing my filter?为什么角度不清除我的过滤器?
【发布时间】:2014-02-12 21:14:07
【问题描述】:

我有一个下拉菜单,用于设置要在 ng-repeat 过滤器中使用的搜索模型对象。

<select ng-model="search.location_id" ng-options="id as name for (id,name) in search_locations">
    <option value="">Location</option>
</select>

我的默认值“位置”也用于清除搜索。问题是当我选择一个位置(正确过滤我的列表),然后返回默认的“位置”选项时,它会清除我所有的 ng-repeat 项目,而不是清除搜索过滤器。

<tr ng-repeat="course in courses | filter:search">

课程对象显然具有 course.location_id 属性。 “search_locations”是要搜索的位置列表,格式为 { id:name , id:name }

如何取回我的完整列表? / 清除这个特定的搜索参数?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    当 angular 运行一个过滤器并且值为 undefined 时,过滤器短路并返回整个列表(如果过滤器值为 null,则此行为相同在角度 1.2 之前)

    您可以做的是向 search_locations 数组添加一个额外的对象,并将 location_id 设置为 undefined:

    $scope.search_locations = [
        { description: 'show all', location_id: undefined },
        { description: 'block 1', location_id: 1 },
        { description: 'block 2', location_id: 2 }
    ];
    

    演示fiddle

    【讨论】:

      【解决方案2】:

      That is because the value assigned to search.location_id when the default option is selected is null and if search.location_id === null, then nothing in your courses list will match (unless, of course course.location_id === null).

      AngularJS docs 上的示例显示默认值为null

      搜索值为null时选择的示例:http://plnkr.co/edit/meKe7l6rubaHEN1eRbzC?p=preview

      模板

       <body ng-controller="MainCtrl">
          <p ng-repeat="item in items | filter:search">
              Id: {{item.id}}, Name: {{item.name}}
           </p>
       </body>
      

      控制器

      app.controller('MainCtrl', function($scope) {
        $scope.items = [{
          id: 1,
          name: 'alice'
        }, {
          id: 2,
          name: null
        }];
      
        $scope.search = {
          name: null
        };
      });
      

      将仅输出items 列表中的第二项。

      要解决此问题,请编写您自己的 filter 函数。

      【讨论】:

      • 感谢您的回复,但我仍然不知道如何找回我的整个 ng-repeat 列表。我觉得这应该是一个普遍的事情。
      • @snowman4415 这是带有 Angular 的 long standing issue,他们决定让 null 仅匹配 null 而不是像 falsey 值一样。您可以编写自己的函数以自定义方式过滤数组使用ng-repeat 创建您想要的option,因为您仅将string 用作values 用于@987654344 @ 而不是对象。
      猜你喜欢
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多