我使用Angular,这是我的观点:
<div class="col-sm-6" ng-repeat="contact in service.contacts">
<label class="control-label mb10">{{contact.textDescription | decodeURIComponent}}</label>
<select multiple="multiple" selectize>
<option>{{contact.value}}</option>
</select>
</div>
我有一个问题,我无法找到解决问题的方法。对于contact.textDescription,我只需要添加唯一值,因此如果该contact.textDescription重复,则不要创建两次字段,但将该contact.value添加到已存在的同一contact.textDescription的选项中。所以,像这样:
if(contact.textDescription is duplicate) {
contact.value.addTo(contact.textDescription which already exists)
}
也许要应用一些过滤器或?
答案 0 :(得分:0)
通过对您提到的内容的理解,我认为以下答案中提到的过滤器将帮助您做您想做的事情
答案 1 :(得分:0)
您可以使用ng-options对特定值进行分组和显示。
答案 2 :(得分:0)
您可以使用angular-filter模块的uniqFilter
用法: collection | unique: 'property'
或nested.property
别名: uniq
示例:强>
的 JS:强>
function MainController ($scope) {
$scope.orders = [
{ id:1, customer: { name: 'John', id: 10 } },
{ id:2, customer: { name: 'William', id: 20 } },
{ id:3, customer: { name: 'John', id: 10 } },
{ id:4, customer: { name: 'William', id: 20 } },
{ id:5, customer: { name: 'Clive', id: 30 } }
];
}
<强> HTML:强>
<th>Customer list:</th>
<tr ng-repeat="order in orders | unique: 'customer.id'" >
<td> {{ order.customer.name }} , {{ order.customer.id }} </td>
</tr>
结果:
客户名单:
- 约翰10
- 威廉20
- 克莱夫30
答案 3 :(得分:0)
按textDescription
对联系人进行分组可以解决您的问题。尝试这样的事情:
HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - GroupBy Filter</title>
<script src="angular-1.4.7.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="MainController">
<div ng-repeat="(key, contacts) in (service.contacts | groupBy: 'textDescription')">
<label class="control-label">{{key}}</label>
<select multiple="multiple" selectize>
<option ng-repeat="contact in contacts">{{contact.value}}</option>
</select>
</div>
</div>
</body>
的script.js:
var app = angular.module("app", []);
app.controller("MainController", function ($scope) {
$scope.service = {};
$scope.service.contacts = [{
"textDescription": "td1",
"value": "1"
}, {
"textDescription": "td2",
"value": "2"
}, {
"textDescription": "td3",
"value": "3"
}, {
"textDescription": "td1",
"value": "4"
}, {
"textDescription": "td3",
"value": "5"
}, {
"textDescription": "td1",
"value": "6"
}];
});
app.filter('groupBy', function () {
var results={};
return function (data, key) {
if (!(data && key)) return;
var result;
if(!this.$id){
result={};
}else{
var scopeId = this.$id;
if(!results[scopeId]){
results[scopeId]={};
this.$on("$destroy", function() {
delete results[scopeId];
});
}
result = results[scopeId];
}
for(var groupKey in result)
result[groupKey].splice(0,result[groupKey].length);
for (var i=0; i<data.length; i++) {
if (!result[data[i][key]])
result[data[i][key]]=[];
result[data[i][key]].push(data[i]);
}
var keys = Object.keys(result);
for(var k=0; k<keys.length; k++){
if(result[keys[k]].length===0)
delete result[keys[k]];
}
return result;
};
});
现在,您按textDescription
分组了所有联系人,因此其字段(<label>
)仅创建一次,并且值将添加到<option>
代码