晚上好! 将用户添加到下拉列表(使用ui-grid)时出现问题。 在点击“addNewPerson”按钮后,如果列表中没有这样的名称,或者调用“alert”(如果有的话),我需要按id将输入名称输入dd列表。
这是一个代码,负责在html中创建dd列表:
<ui-select ng-model="person.selected" theme="select2" style="min-width:300px;">
<ui-select-match placeholder="Select a person in the list or search by name">{{$select.selected.name}}
</ui-select-match>
<ui-select-choices repeat="person in contacts | filter: {name: $select.search} track by $index">
<div ng-bind-html="person.name | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>
按钮和输入栏:
<button type="button" id="addPerson" class="button" ng- click="addNewPerson()">Add New Person</button>
<input id="name" class="form-control" placeholder="Enter your Name">
具有“name”字段的对象数组,需要将其传递到dd列表中:
$scope.contacts = [
{name: "Han Solo"},
{name: "ThetaSigma"},
{name: "Ollie Reeder"},
{name: "Amy McDonald"},
{name: "PJ Harvey"},
{name: "Sofie Marceau"},
{name: "Arthur Zimmermann"},
{name: "Michelle Dockery"},
{name: "Xavier Dolan"}
];
最后,臭名昭着的功能:
$scope.person = {};
$scope.addNewPerson = function () {
var nameInput = document.getElementById("name");
for (var i=0; i <= $scope.contacts.length; i++) {
if ($scope.contacts[i].name == nameInput.value.toLowerCase()) {
alert("Error, the name entered already exists");
}else{
var obj1 = {name: nameInput.value};
$scope.contacts.push(obj1);
}
}
};
我尝试了各种功能,它可以不进行任何操作并提醒10次,或者正确推送名称,但即使已经存在,也可以推送10次,并在单次添加后提醒10次。
我有残障。试图在这里找到类似的q / a,但无济于事。 抱歉我的英语,这不是我的母语。
答案 0 :(得分:1)
此处有biased random number generator个例子。
首先更改输入的html以使用范围变量:
<input ng-model="name" class="form-control" placeholder="Enter your Name">
并在控制器中:
$scope.name = "";
$scope.addNewPerson = function () {
for (var i=0; i < $scope.contacts.length; i++) {
if ($scope.contacts[i].name.toLowerCase() === $scope.name.toLowerCase()) {
alert("Error, the name entered already exists");
return;
}
}
$scope.contacts.push({name: $scope.name});
};
答案 1 :(得分:0)
你绑定新用户名的模型:
<input id="name" class="form-control" placeholder="Enter your Name" ng-model="new_user_name">
然后在你的js中,你必须打破你的forloop:
$scope.person = {};
$scope.addNewPerson = function () {
var name = $scope.new_user_name || "";
var match_found = false;
for (var i=0; i <= $scope.contacts.length; i++) {
if ($scope.contacts[i].name == name.toLowerCase()) {
alert("Error, the name entered already exists");
match_found = true;
break;
}
}
if (!match_found) {
var obj1 = {name: name};
$scope.contacts.push(obj1);
}
};
答案 2 :(得分:0)
上面的答案很好,我只想添加使用函数编程风格的选项,因为我喜欢这样做,对我来说它看起来更干净。
<input ng-model="name" class="form-control" placeholder="Enter your Name">
$scope.name = "";
$scope.addNewPerson = function () {
var contactIndex = $scope.contacts.map(function (contact) {
return contact.name.toLowerCase();
}).indexOf($scope.name.toLowerCase());
if (contactIndex === -1)
$scope.contacts.push({name: $scope.name});
else
console.log("Error, the name entered already exists");
}
一些注意事项: