dropdown value disappears when select - angularjs

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"

Related

Show JSON data in multi select box

I got some problem as I am new in Angular. I tried to show one of the JSON key value in multi select box options but failed to load.
I had gone through the example over here and I am doing same function by clicking button.
http://plnkr.co/edit/TdueXL8BQTi8DOodnD5q?p=preview
So the controller part :-
$scope.master = {};
$scope.addValue = function(ff) {
$scope.master = angular.copy(ff);
$http.post("url", $scope.master).success(function(data) {
$scope.use= data;
console.log("Successful");
},function (data, status, headers, config) {
console.log("something went wrong");
});
console.log($scope.master);
};
So my master={} is binding user input in JSON value ie; {"Name":"","Motor":"","Company":""} . I want to show Name only, on repeat.
View is :-
<select multiple="multiple" id="reg_select_multiple" class="form-control">
<option ng-repeat="x in master" value="{{x.name}}"></option>
</select>

Retrieve Selected Option Value From HTML DropDownList

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.

ngModel doesn't bind to select option

I can't figure out why i can't bind to a select element
there is my code:
<select ng-model="site" ng-change="getAll()">
<option value="SG1">SG1</option>
<option value="PZ1">PZ1</option>
<option value="NE1">NE1</option>
</select>
getAll() make an alert of 'site' but the var is never updated.
$scope.site is nerver use except in getAll()
$scope.getAll = function () {
alert($scope.site);
}
If i set $scope.site to a value it is display but never update either
Edit:
I forgot a big detail...
The select is display with a ng-include directive
<section id="sectionLeft" ng-include="nav[navId]">
</section>
ng-include creates a new scope which prototypally inherits from your controller. So you are initially reading the selected option from your controller, but when the select element writes a new selected option it ends up writing to the inherited scope.
You can bind to an object instead.
Controller:
$scope.data = { site: "SG1" };
$scope.getAll = function() {
alert($scope.data.site);
}
Template:
<select ng-model="data.site" ng-change="getAll()">
<option value="SG1">SG1</option>
<option value="PZ1">PZ1</option>
<option value="NE1">NE1</option>
</select>
See this answer for more details.
If you don't like switching to an object, look up controller as syntax and bind directly to the controller instead of $scope.
I've fiddled your code and i'm able to get the updated value in the alert box.
$scope.getAll = function() {
alert($scope.site);
};
Working Fiddle

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: after ng-change 1st select is getting empty

I am using following code to get data from local json file and populating two dropdowns from it but after ng-change event fires 1st dropdown is empty.
$http({method: 'GET', url: 'data/local.json'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
var _data=data;
$scope.places=[];
$scope.toPlaces=[];
$scope.places=data;
$scope.getToPlaces=function(){
var selected=$('#fromSelect :selected').val();
console.log($scope.places[1]);
var key=$scope.places[1]
$scope.toPlaces = _data[key].to;
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert("failure");
});
I am using code from this link: https://github.com/marcoslin/angularAMD and passing json file from my local machine.
After ng-change 1st select is getting empty.
The problem is within your markup:
From angular docs:
When an item in the menu is selected, the array element or object property represented by the selected option will be bound to the model identified by the ngModel directive.
This is the reason why it overrides the places array when it is selected.
The ngModel directive inside a select tag should just refer to another variable on the scope:
<select ng-model="selectedPlace" ng-change="getToPlaces()" id="fromSelect">
<option value="">--Please select From place</option>
<option ng-repeat="p in places" value="{{p.id}}">
{{p.name}}
</option>
</select>
Now instead of var selected=$('#fromSelect :selected').val(); , You can just refer to that varaible:
var selected = $scope.selectedPlace;

Resources