角度简单国家过滤器(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
更多推荐
发布评论