【问题标题】:How to create filter in Angularjs?如何在 Angularjs 中创建过滤器?
【发布时间】:2015-11-15 22:52:29
【问题描述】:

我有这些课程:

 [{ id: 1, courseId: 2, text: 'John' },
  { id: 2, courseId: 2, text: 'Willi' },
  { id: 3, courseId: 2, text: 'Inga' },
  { id: 4, courseId: 1, text: 'Jerry' },
  { id: 5, courseId: 1, text: 'Michael' },
  { id: 1, courseId: 3, text: 'John' },
  { id: 2, courseId: 3, text: 'Willi' },
  { id: 3, courseId: 4, text: 'Inga' },
  { id: 4, courseId: 5, text: 'Jerry' },
  { id: 5, courseId: 5, text: 'Michael' }]

我有这个 id 数组:

[{"id": 3},{"id": 2},{"id": 1}] 

我需要通过 id 数组过滤课程数组(即仅显示具有 courseId = 3,2,1 的文本课程):

ng-repeat="course in courses| customFilter: [{"id": 3},{"id": 2},{"id": 1}]"

我需要在 angularJS 中创建自定义过滤器,该过滤器将按 id 数组过滤课程数组。

知道如何为此目的实现 customFilter 吗?

【问题讨论】:

标签: javascript angularjs data-binding angularjs-filter


【解决方案1】:

您可以创建您的自定义filter,以便为您提供过滤后的值,过滤器应该将元素数组作为过滤器数组。

标记

ng-repeat="course in courses| customFilter: [{"id": 3},{"id": 2},{"id": 1}]""

过滤器

app.filter('customFilter', function(){
  return function(array, filterArray){
     var ids = [];
     angular.forEach(filterArray, function(val, index) {
        ids.push(val.id);
     }
     return array.filter(function(value){
        return ids.indexOf(value.id) !== -1;
     });
  }
})

【讨论】:

  • ,我有这个格式过滤器:customFilter: [{"id": 3},{"id": 2},{"id": 1}]" 不是这个:customFilter: [3 ,2,1]"
  • 为什么需要这种过滤器..为什么不简化它??
  • 因为这个结果是我从服务中得到的。我需要把它保存在上面的格式中
  • 虽然我已经做出了相应的更改..看看他们。
  • 感谢您的帮助,但似乎有一些错误
【解决方案2】:

我在 angularJs 项目中创建了一个过滤器。

在我的 Angular 应用程序名称中是 angularApp。

var app = angular.module('angularApp', []); // This is your main angular app.

现在您要为解码 url 创建一个过滤器。

app.filter('decodeURL', function() {
    return function(text) {
        if(text) {
            return text.split(' ').join('-').toLowerCase().replace(/[^a-z0-9]+/g, '-');
        }
    }
});

上面的代码是创建一个过滤器来解码url。我的过滤器名称是 'decodeURL' 。我们将在我的代码中使用 decodeURL 作为过滤器 比如你的网址是-

http://www.example.com/test1test2 tes3

然后过滤使 URL 像这样-

http://www.example.com/test1-test2-tes3

如何在html中使用这个过滤器-

<a ui-sref="{{business.category[0].categoryName.toLowerCase()}}Detail({id:business.id,title:(business.title | decodeURL)})"></a>

//以上是angularjs中的状态路由。

<a href="/coupon/{{coupon.id}}/{{coupon.title | decodeURL}}"
                                       class="btn btn-warning show-btnhome show-button-margin">Show</a>

//上面的URL重定向代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2016-03-21
    • 2012-12-13
    • 2014-09-14
    相关资源
    最近更新 更多