Retrieve Selected Option Value From HTML DropDownList - angularjs

I've a DropDownList where user has to select options and save it to database. I am using the following with AngularJs:
<select>
<option>----Please Select Sub-Category----</option>
<option ng-repeat="m in Categories" value="{{ m.CategoryId }}" ng-model="saveProducts.CategoryId">{{ m.Category }}</option>
</select>
I can show the values in the above DropDownList but stuck to retrieve the value from the selected and pass it to the scope. I've tried even this, a silly one:
<select>
<option>----Please Select Sub-Category----</option>
<option ng-repeat="m in Categories" value="{{ m.CategoryId }}" ng-model="m.CategoryId">{{ m.Category }}</option>
</select>
But that will not work. saveProducts is the object (scope) where I am passing values but is there any easy way where I can pass option value with the above procedure?
Here what I am doing to save data in database and it works fine except the option value, it's unable to retrieve values with the above:
productApp.controller('addProductController', function ($scope, $http) {
$scope.addData = function () {
$http({
method: 'POST',
url: '/Product/AddProductsToDb',
data: $scope.saveProducts
}).success(function () {
$scope.saveProducts = null;
}).error(function () {
alert('Failed');
});
}
});
This is the output I have and just want to pass the option value from it:
Update 1 - This is what I've tried but I can show the value in the alert method using as follows:
<select ng-model="saveProducts.ParentId"
ng-options="m.Category for m in Categories track by m.CategoryId">
<option value="">----Please Select Sub-Category----</option>
</select>
AngularJs Controller:
productApp.controller('addProductController', function ($scope, $http) {
$scope.addData = function () {
angular.forEach($scope.saveProducts, function (model, index) {
$scope.saveProducts.ParentId = (model.CategoryId);
});
alert($scope.saveProducts.ParentId);
$http({
method: 'POST',
url: '/Product/AddProductsToDb',
data: $scope.saveProducts
}).success(function () {
$scope.saveProducts = null;
}).error(function () {
alert('Failed');
});
}
});
Note: It saves TextBox input value but stuck with DropDownList. Unable to retrieve select option value and save it to database.

You should have a property to store the selected option. You can use ng-options to render the dropdown.
<select ng-model="selectedCategory"
ng-options="option.Category for option in Categories track by option.CategoryId ">
<option value="">Select Option</option>
</select>
Now your select element's ng-model is set to selectedCategory. So in your add method you can access that and use that for saving.
$scope.addData = function () {
console.log($scope.selectedCategory);
//to do : use selectedCategory
}

Use ngOptions. Depending on the structure of your Categories data, you could do something like:
<select ng-options="m as m.yourProperty for m in Categories" ng-model="selected"></select>
Then, in Angular...
$scope.selected = $scope.Categories[0];
Read the ngOptions documentation to tweak according to your needs.

Related

Angular populate from JSON through httpd and then choose selected

I'm fairly new to Angular and i'm trying to do something quite simple. I want to populate a dropdown box and have the selected value from database as selected option. Here is my dropdown code.
<select ng-options="option.fname+' '+option.lname for option in students track by option.id"
class="form-control"
name="studentId"
ng-model="selectedStudent"
id="studentId"
ng-change="loadStudent()"
>
<option value="">Please choose a student</option>
</select>
Now, in my module and the controller, i have this code which populates the dropdown and i can see the options (student.id, student.fname , student.lname):
$scope.students = {};
$scope.selectedStudent = null;
$scope.populateStudents = function() {
$http({
method: 'POST',
url: 'ajax/getStudents',
data: { teacherId: 0 }
}).success(function (result) {
$scope.students = result;
$scope.selectedStudent = 4;
});
}
This runs i guess on page load as i have this :
Then on the above script and after the $scope.students is loaded, i write
$scope.selectedStudent = 4; which I want to preselect the student with student.id = 4.
What happens though is that the default
<option value="">Please choose a student</option> is becoming <option value="" select="selected">Please choose a student</option> instead of the student with id 4.
What am I doing wrong ?
Thank you.
When you use ngOptions with an array of complex objects, you must use an identical complex object to "select" one of the options, not just a number. So, once your $http call has returned, find the item in the list with the id you want and assign your scope variable to be the entire student object:
$http({
method: 'POST',
url: 'ajax/getStudents',
data: { teacherId: 0 }
}).success(function (result) {
$scope.students = result;
angular.forEach($scope.students, function(student) {
if (student.id == 4) {
$scope.selectedStudent = student;
}
});
});
If you add the as statement to your ng-repeat you can select the student by id like so:
<select ng-options="option.id as option.fname+' '+option.lname for option in students track by option.id"
class="form-control"
name="studentId"
ng-model="selectedStudent"
id="studentId"
ng-change="loadStudent()"
>
<option value="">Please choose a student</option>
</select>
$scope.selectedStudent = { id: 4 };
I prefer to use lodash or underscore to find an item in a list rather than using forEach:
$scope.selectedStudent = lodash.find($scope.students, { 'id': 4 });

dropdown value disappears when select

I have one select in which I bind data from database by get method.it binds data perfectly in select.but when I select one of it option .its disappears..any help appreciated.
This is my HTML Code:
<select class="form-control" ng-model="MainCategory" ng-options="main.Name for main in MainCategory track by main.ID" placeholder="Select Main Category">
<option value=""></option>
</select>
this is my contoller code
var baseURL = 'http://localhost:50928/api/ProductAPI/';
var MainCategory = [];
url = baseURL + "GetMainCategoryList";
$http.get(url)
.success(function (data) {
$scope.MainCategory = data;
console.log(data);
}).error(function (data) {
console.log(data);
});
Your ng-options data is MainCategory and your ng-model is binded to it as well. This means that selecting an options turns your data to one value only - your selected option. In your case you should have a data property, lets say - categories.
Like this:
ng-options="main.Name for main in categories track by main.ID"
In addition you will hold in your controller another property for the selected Category and ng-model will bind to it:
ng-model="selectedCategoty"

angular select default to first option

I cannot seem to get my dropdown to default to having the first store selected.
html:
<select
id="store"
class="form-control input-inline input-medium"
ng-model="orderVm.Stores.selectedStore.id">
<option
ng-repeat="store in orderVm.Stores"
value="{{store.Id}}">
{{store.MarketplaceName}}
</option>
</select>
{{orderVm.Stores.selectedStore}}
vm.Stores (loaded from a local JSON file):
[
{
"Id": 1,
"MarketplaceId": 1,
"MarketplaceName": "Etsy"
]
},
{
"Id": 2,
"MarketplaceId": 2,
"MarketplaceName": "Shopify"
}
]
controller:
angular
.module('WizmoApp')
.controller('orderController', orderController);
orderController.$inject = ['$http', '$location', 'toastr', 'DTColumnDefBuilder', 'DTOptionsBuilder', 'Cart', 'OrderService', 'PackageService'];
function orderController($http, $location, toastr, DTColumnDefBuilder, DTOptionsBuilder, Cart, OrderService, PackageService) {
var vm = this;
vm.Stores = json; //from file
vm.Stores.selectedStore = {
id: vm.Stores[0].Id,
name: vm.Stores[0].MarketplaceName
};
OrderService.getOrdersGroupedByStore(function (json) {
vm.Stores = json;
vm.selectedStore = {};
});
routes.js:
.state('layout.orders', {
url: '/orders',
templateUrl: '/Content/js/apps/store/views/order.html',
controller: 'orderController',
controllerAs: 'orderVm',
data: { pageTitle: 'Orders' }
})
(It doesn't help that the first option is blank, but first things first.)
I'd use ng-options but frankly, it's even more obscure than this.
https://jsbin.com/kanaco/edit?html,js,output
I write a sample code for you.
Use ng-options for select.
edit:
<select id="store" class="form-control input-inline input-medium"
ng-model="ctrl.selectedStores"
ng-options="item.MarketplaceName for item in ctrl.Stores"
ng-init="ctrl.selectedStores=ctrl.Stores[0]">
</select>
You can use ng-options for repeat option, and use ng-init for default select.
Never use ng-repeat to build select options. Instead, use ng-options, which has a dedicated directive for this:
<select
id="store"
class="form-control input-inline input-medium"
ng-model="orderVm.Stores.selectedStore"
ng-options="store.ID as store.MarketplaceName for store in orderVm.Stores">
</select>
In your controller, you need to assign a default value to the select model:
orderVm.Stores.selectedStore = 1;
This would cause the Etsy option to be selected when the controller loads. Note that the model is just an id here, you don't need to use an object. The reason you were getting an empty option is that Angular could not bind the model to any of the options.
I had a very similar problem to yours and was asissted by a kind guru.

Responding to drop down selection change in angular without model binding

I have a drop down that should cause a data fetch on change. I don't need two way binding to a model for the drop down. I just want it initially populated with a list of departments and when a user selects one, it gets the list of users in that department.
The select looks like this:
<select class="form-control" id="selDepartmentList" ng-model="departmentList" ng-change="getUsersInDepartment(document.getElementById("selDepartmentList").options[document.getElementById("selDepartmentList").selectedIndex].value)">
<option value="-1">All</option>
<option ng-repeat="dept in departmentList"
value="{{dept.DepartmentId}}">
{{dept.DepartmentName}}
</option>
</select>
I tried ng-change without ng-model, but it fails since ng-change requires ng-model for some reason. I tried setting ng-model to null and empty string, but neither worked. I also tried not using ng-change at all and using onchange, but getUsersInDepartment can't be found through onchange since it's attached to my controller. With ng-model set to departmentList, the drop down won't hold a value, any selection is erased.
All I want to have happen is that when a user selects a department it passes the id for that department to getUsersInDepartment, which will then fetch the user list. But right now getUsersInDepartment is never called.
departmentList is defined in my controller and attached to $scope. All the examples I've seen have some kind of selectedModelObject that they bind to the drop down. I don't have one of those.
My controller looks like:
controller('AdminTableCtrl', function ( $scope, coreAPIservice ) {
$scope.userList = [];
$scope.departmentList = [];
coreAPIservice.GetUserList().success(function (response) {
$scope.userList = response;
});
coreAPIservice.GetDepartmentList().success(function (response) {
$scope.departmentList = response;
});
$scope.getUsersInDepartment = function(deptId) {
if(deptId === -1) {
coreAPIservice.GetUserList().success(function (response) {
$scope.userList = response;
});
}
else {
coreAPIservice.GetUsersInDepartmentList(deptId).success(function (response) {
$scope.userList = response;
});
}
}
});
Edit:
My original attempt with ng-options:
<select class="form-control" id="selDepartment"
ng-model="selectedDepartment"
ng-options="dept as dept.DepartmentName for dept in departmentList track by dept.DepartmentId">
<option value="">Select Team...</option>
</select>
selectedDepartment is defined as:
$scope.selectedDepartment = {};
The solution is to avoid decorating the <select> element with any angular directives and instead place ng-click on each <option>.
Like this:
<select class="form-control" id="selDepartmentList">
<option value="-1" selected>All</option>
<option ng-repeat="dept in departmentList"
ng-click="getUsersInDepartment(dept.DepartmentId)"
value="{{dept.DepartmentId}}">
{{dept.DepartmentName}}
</option>
</select>
Making a custom directive should work for this problem.
angular
.module('my_module')
.directive('ngCustomChange', function($parse) {
return function(scope, element, attrs) {
var fn = $parse(attrs.ngCustomChange);
element.bind('change', function(event) {
scope.$apply(function() {
event.preventDefault();
fn(scope, {$event:event});
});
});
};
});
<select ng-custom-change="$ctrl.myFunction()">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>

angularjs remove duplicate values from ngrepeat

I am trying to get a category dropdown list fetched from below JSON data. I have same category multiple times, For Ex: Computer
[
{
"title":"C Programming",
"category":"Computer"
},
{
"title":"International Tax",
"category":"Business"
},
{
"title":".net Programming",
"category":"Computer"
}
//more data...
]
AngularJS:
function showSubjects($scope, $http)
{
$http({method: 'POST', url: 'js/subjects.json'}).success(function(data)
{
$scope.items= data; // response data
});
}
HTML:
<div id="ng-app" ng-app ng-controller="showSubjects">
<select>
<option ng-repeat="subjects in items">{{subjects.category}}</option>
</select>
</div>
I want to display duplicate categories only once. Please give me some suggestions, how to acheive the required output. Thanks in advance.
Use
<option ng-repeat="subjects in items | unique:'category'">{{subjects.category}}</option>
Look here for more: Unique & Stuff
You can use your own function like below:
<select name="cmpPro" ng-model="test3.Product" ng-options="q for q in productArray track by q">
<option value="" >Plans</option>
</select>
productArray =[];
angular.forEach($scope.leadDetail, function(value,key){
var index = $scope.productArray.indexOf(value.Product);
if(index === -1)
{
$scope.productArray.push(value.Product);
}
});

Resources