有什么方法可以限制 AngularJS 中重复的项目数量吗?就像在联系人列表中一样,我需要输入相同的姓名和联系电话,但只需要输入两次,当我尝试第三次输入时,它会显示一些警告,表明您已经输入了联系方式。如何使用 AngularJS 或 JavaScript 来完成此任务?
我的代码是
<md-list-item ng-show="showContactList" ng-repeat="numbers in contactList track by $index" >
<i ng-show="numbers.type == 'test'">textsms</i>
<i ng-show="numbers.type == 'CELL' || numbers.type == 'EXT'">phone</i>
<img ng-show="numbers.type == 'PAGER'" src="pager.png" width="26">
<div class="md-list-item-text" ng-class="{'md-offset': phone.options.offset }">
<h3>{{ numbers.type }}</h3>
<p>{{ numbers.value }}</p>
</div>
<i ng-click="arrayText.push(numbers);">add</i>
</md-list-item>
在上面的代码中,我可以向联系人姓名和号码添加 N 个号码。
最佳答案
试试这个
HTML
<i class="material-icons md-avatar-icon add-rm-icon margin-right" ng-click="insertRecord(numbers);">add</i>
Controller
var existed = 0;
$scope.insertRecord = function(numbers){
var name = numbers.type;
angular.forEach($scope.arrayText, function(value, key) {
var arr = Object.values(value);
if(arr.indexOf(name) !== -1 ) {
existed++;
console.info(existed);
}
});
if(existed >= 2){
console.info('already exist')
existed = 0;
}else{
$scope.arrayText.push(numbers);
existed = 0;
}
}
在 var name
变量中,您可以放置要检查两次插入的属性。
关于javascript - 有没有办法限制 ng-repeat 中重复项目的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42344138/