简体   繁体   English

angularJs $ filter JavaScript语法

[英]angularJs $filter javascript syntax

Tried to filter a JSON file by $routeParams:id. 试图通过$ routeParams:id过滤JSON文件。 usually I do this: 通常我这样做:

var eventId = $routeParams.eventId;
$http.get('json/events.json')
 .success(function(data){
     angular.forEach(data,function(d){
         if(d.id == eventId)$scope.event = d;
     });

}); 

found some working code that doing this: 找到了一些执行此操作的代码:

var eventId = $routeParams.eventId;
$http.get('json/events.json')
 .success(function(data){
    $scope.template = $filter('filter') (data, function(d){
    return d.id == eventId;
    })[0];
}); 

can you explain the syntax on the second example? 您可以在第二个示例中解释语法吗? especially the square brackets notation after the function call? 特别是函数调用后的方括号表示法? and which approach is better ? 哪种方法更好?

Thanks 谢谢

I think first approach is better for this purpose. 我认为第一种方法更适合此目的。 $filter mainly used for templates.for example if you want to use filter in ng-repeat directive. $filter主要用于模板。例如,如果要在ng-repeat指令中使用filter
in second example $filter returns an array of filtered data. 在第二个示例中,$ filter返回一个过滤数据数组。 you assigning the first element via [0] in the end. 您最后通过[0]分配了第一个元素。 this might cause a range error if there is no data in that filtered array. 如果该筛选数组中没有数据,则可能会导致范围错误。

to ignore that error you might use 忽略您可能使用的错误

var filteredTemplates = $filter('filter') (data, function(d){
    return d.id == eventId;
    });
   $scope.template = (filteredTemplate.length && filteredTemplate[0])|| default_template;

and there is only a conditions to check so no need to use filter just loop through it, if you can't find the multi use, of filter you created. 而且只有一个条件需要检查,因此不需要使用过滤器就可以遍历它(如果找不到多用途),即创建的过滤器。

EDIT : accessing the first element of an empty array will not throw error but returns undefined 编辑 :访问一个空数组的第一个元素不会引发错误,但返回undefined

Filters are used for formatting data displayed to the user.And its main purpose to format the data displayed in Angular template. 过滤器用于格式化显示给用户的数据,其主要目的是格式化Angular模板中显示的数据。 $filter is a filter service of angular module.It holds reference to all the filters. $ filter是角度模块的过滤器服务,它包含对所有过滤器的引用。

$filter('nameOfTheFilter')(array, expression, comparator) 

Here you are getting default filter from filter service and passing in an array and an iterator function that will be called for each element in the array. 在这里,您将从过滤器服务获取默认过滤器,并传入一个数组和一个迭代器函数,该函数将为数组中的每个元素调用。 And $filter('filter') returns an array, that satisfy the return condition in the iterator function.you are assigning the fist element of the filtered array to $scope.template.It may assign undefined if an empty array is returned by the filter $ filter('filter')返回一个满足迭代器函数返回条件的数组。您正在将过滤后的数组的第一元素分配给$ scope.template。过滤

  $filter('filter') (data, function(d){
    return d.id == eventId;
    })[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM