角度简单国家过滤器(Angular Simple Country Filter)

系统教程 行业动态 更新时间:2024-06-14 16:55:57
角度简单国家过滤器(Angular Simple Country Filter)

说你有

$scope.countries = [ { id="7AFG", name="Afghanistan"}, { id="1B1", name="Albania"}, { id="4AL", name="Algeria"}, { id="1B2", name="Andorra"} ]

依此类推,并且在您的视图中,您正在显示的产品的countryID与上面显示的ID相对应。 例如

{{ product.address.countryID}}

这将是“1B1”或其他一些。 从列表中获取国家/地区名称值的最有效方法是显示而不是ID?

我是否需要编写自定义过滤器然后应用它

{{product.address.countryID | myCountryFilter }}

还是有一种我更容易忽视的方式?

Say you have

$scope.countries = [ { id="7AFG", name="Afghanistan"}, { id="1B1", name="Albania"}, { id="4AL", name="Algeria"}, { id="1B2", name="Andorra"} ]

and so on, and in your view you are displaying a product which has a countryID which would correspond with the ids shown above. For example

{{ product.address.countryID}}

which would be "1B1" or some such. What's the most efficient way to have the country name value from the list, to be displayed instead of the ID?

Do I need to write a custom filter and then apply it such as

{{product.address.countryID | myCountryFilter }}

or is there a more straightforward way that I am overlooking?

最满意答案

您可以将数据放入工厂并使用自定义过滤器。

angular.module('myApp',[]) .factory('countriesFactory', function() { var data = [ { id:"7AFG", name:"Afghanistan"}, { id:"1B1", name:"Albania"}, { id:"4AL", name:"Algeria"}, { id:"1B2", name:"Andorra"} ]; return data; }) .filter('countryFilterById', function($filter, countriesFactory) { return function(id, keyStrToReturn) { var filtered = $filter('filter')(countriesFactory, {'id':id}) if(filtered.length < 1){ return null; } if(keyStrToReturn){ return filtered[0][keyStrToReturn]; } return filtered[0]; } }) .controller('MyCtrl', function($scope, countriesFactory) { $scope.currentProductId = '1B1'; // for that demo });

看到这个小提琴: 过滤你的国家

You could put your data in a factory and use a custom filter.

angular.module('myApp',[]) .factory('countriesFactory', function() { var data = [ { id:"7AFG", name:"Afghanistan"}, { id:"1B1", name:"Albania"}, { id:"4AL", name:"Algeria"}, { id:"1B2", name:"Andorra"} ]; return data; }) .filter('countryFilterById', function($filter, countriesFactory) { return function(id, keyStrToReturn) { var filtered = $filter('filter')(countriesFactory, {'id':id}) if(filtered.length < 1){ return null; } if(keyStrToReturn){ return filtered[0][keyStrToReturn]; } return filtered[0]; } }) .controller('MyCtrl', function($scope, countriesFactory) { $scope.currentProductId = '1B1'; // for that demo });

See this fiddle : filtering your countries

更多推荐

本文发布于:2023-04-10 11:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/182b8ccd926f69582559396d91b48b59.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   角度   简单   国家   Filter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!