在从数组中过滤空字符串后,仅显示第一个和最后一个重复的元素会有一些问题。
我的代码:
var myApp = angular.module('myApp', []);
myApp.controller("myCtrl", function ($scope, $window) {
$scope.items = [
{ name: "item1", color: "green", form: "" },
{ name: "item2", color: "", form: "circle" },
{ name: "item3", color: "red", form: "" },
{ name: "item4", color: "", form: "oval" },
{ name: "item5", color: "blue", form: "" },
{ name: "item6", color: "", form: "square" },
{ name: "item7", color: "yellow", form: "" },
{ name: "item8", color: "", form: "rectangle" }
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl" class="ng-scope">
<div ng-repeat="item in items" ng-if="item.form == ''">
{{item.name}}-{{item.color}}
</div>
<br />
<div ng-repeat="item in items" ng-if="item.color == ''">
{{item.name}}-{{item.form}}
</div>
<br />
</body>
但我只需要显示列表中的第一和最后一个。前任。在第一个列表中:item1-green和item7-yellow(必须隐藏item3-red和item5-blue),第二个列表中的item2-circle和item8-rectangle。
我为您的用例创建了自定义过滤器。基本上,过滤器将通过过滤传递的参数(形式和颜色)的空值来返回数组。
过滤后,您可以使用$first
,并$last
与ng-if
只显示第一和最后一个元素。
请参阅下面的代码。
var myApp = angular.module('myApp', []);
myApp.filter('customFilter', function() {
return function(input, param) {
if(input.length == 0) { return [];}
var result = [];
angular.forEach(input, function(item) {
if(item[param] && item[param]!= '') {
result.push(item);
}
});
return result;
}
})
myApp.controller("myCtrl", function ($scope, $window) {
$scope.items = [
{ name: "item1", color: "green", form: "" },
{ name: "item2", color: "", form: "circle" },
{ name: "item3", color: "red", form: "" },
{ name: "item4", color: "", form: "oval" },
{ name: "item5", color: "blue", form: "" },
{ name: "item6", color: "", form: "square" },
{ name: "item7", color: "yellow", form: "" },
{ name: "item8", color: "", form: "rectangle" }
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl" class="ng-scope">
<div ng-repeat="item in items | customFilter:'color'" ng-if="$first || $last">
{{item.name}}-{{item.color}}
</div>
<br />
<div ng-repeat="item in items | customFilter:'form'" ng-if="$first || $last">
{{item.name}}-{{item.form}}
</div>
<br />
</body>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句