Reputation: 509
I am developing an app in AngularJS.
1. I would like to know how can I disable a button if the input value typed by the user is not a item of the uib-typeahead
list (in this case the Array items
)? And enable it when it is a item of the array?
2. And also, how can I disable the same button when the user tries to add a item of the Array items
through the Add button that was already added? The items are saved in the Array addedItems
.
This is the input and button in HTML:
<input type="text" ng-model="search1" uib-typeahead="item for item in items
| filter:$viewValue | limitTo:10"/>
<button type="submit" class="btn btn-success" ng-click="action()"
ng-disabled="(!search1)">Add</button>
This is a sample of the items
Array structure:
var items = ["admin1", "admin2", "admin3", "admin4", "admin5"];
The action()
function is defined in the controller in JavaScript:
$scope.items = ["admin1", "admin2", "admin3", "admin4", "admin5"];
$scope.search1 = undefined;
$scope.addedItems = [];
$scope.action = function() {
$scope.addedItems.push($scope.search1);
}
Thank you *
Upvotes: 0
Views: 1038
Reputation: 129
I'm not sure if I can completely understand what do you want do. Let me try.
$scope.items = ["admin1", "admin2", "admin3", "admin4", "admin5"];
$scope.search1 = undefined;
$scope.addedItems = [];
//this method will help you know if the item exists already in the list
$scope.exists = function(list, item){
return list.indexOf(item) > -1;
}
$scope.action = function() {
$scope.addedItems.push($scope.search1);
}
After you can use the method to enable or disable the button like this:
<button type="submit" class="btn btn-success" ng-click="action()"
ng-disabled="exists(addedItems, search1)">Add</button>
I hope this may help you!
Upvotes: 1
Reputation: 410
- I would like to know how can I disable a button if the input value typed by the user is not a item of the uib-typeahead list (in this case the Array items)? And enable it when it is a item of the array?
In your case ui-select will fit your need.
- And also, how can I disable the same button when the user tries to add a item of the Array items through the Add button that was already added? The items are saved in the Array addedItems.
There are couple ways of doing it.
1. Add a ng-change
method to your input and inside the method do your unique check. Then bind the unique check result to the ng-disabled
in the button.
2. This will be reusable but bit more complicated. Have a custom unique check directive that takes a list and an input. And have the button listen to the error. Something like ng-disabled="form.search1.$unique"
Upvotes: 0