Variations for dropdown in AngularJS
Posted By : Abhinav Anand | 23-Dec-2014
There are so many ways to create a drop down box for selection in angularjs,but we have to google or search here and there for the exact solution for variations at drop-down.
I also faced such a problem,so i tried to get the things at one place so that you can easily find solution for your need.
1>Simple way to generate a drop-down is by using ng-repeat.
In your Angularjs controller
$scope.items = ['chairs','fruits','balls','cars']
This code is useful when the array items only contains string data.But, this way can't be used when array contains objects.
2>If we have use ng-options as.
A>select as label for value in array.
$scope.items = [{name: 'car', quantity: 10 },{ name: 'fruits', quantity: 20 },{ name: 'gifts', quantity: 40 }];
Initially the first option inside the dropdown box is a blank. This is because, initially, the ‘selectedItem’ does not have any default value and is undefined. Hence no default option pre-selected, AngularJS will generates a new option tag and select it as default. In oreder to fix the problem, just set the ‘selectedItem’ to the first object in the array.
$scope.selectedItem = $scope.items[0]
B> label group by group for value in array
$scope.items = [{name: 'car', quantity: 10 },{ name: 'fruits', quantity: 20 },{ name: 'gifts', quantity: 40 },{name: 'bat', quantity: 10 }, {name: 'flowers', quantity: 10 },{name: 'books', quantity: 10 }];
Then select syntax will be
B>select as label group by group for value in array track by trackexpr
For object data
A>If we have items as object,We can use
label for (key , value) in object
$scope.items = {'fruits': 50,'car': 77,'flowers': 40,'balls': 85,'bats': 27,'gifts': 30 };
Select syntax will be
Hope this will be very useful for you.
Thanx
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Abhinav Anand
Abhinav is a bright web developer with expertise in groovy and grails frameworks. His hobbies are listening music and playing cricket.