Angular ng-option index issue - angularjs

I am stuggling with ng-options in Angular version 1. The issue is a follows:
I have a json file that I read to populate a drop-down select:
$http({method: 'GET', url: 'collection_countries.json'})
.then(function successCallback(response) {
$scope.collection_countries = response.data;
$scope.collection_country=$scope.collection_countries[0]; // pre-seelct
}
);
I then generate the drop down as follows:
<select class="form-control" name="deliver_to" ng-model="destination_country" ng-options="item as item.country for item in countries track by item.id" required>
<option value="" disdabled>Select Country</option>
</select>
This works ok to this point, however I am trying read the selected value and corresponding data form the json as follows:
$scope.countries[ $scope.destination_country['country']['id'] ];
As you can see the value $scope.destination_country['country']['id'] is the id which is arbitrary and does not correspond with the index of the json object.
As I see it I have two options:
In the ng-options directive I track by $index (or similar as I know $index is for ng-repeat and not ng-options)
Some how reference the json object by the country_id
I created this plunkr to demonstrate the issue.
https://plnkr.co/edit/19H8A12VnVpdlHQe5vM7?p=preview
Thanks.

Related

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.

Angular Js ng-change function runs on load

I have Select box on which i have called a function on ng-change, but don't know why it run when page load. I don't want that function to call on load. I think it is not basic behaviour of ng-change.
<select class="form-control" name="state" id="state_id" ng-model="form.state" ng-change="getStateList(form.state)">
<option value="">Select State</option>
<option ng-repeat="states in state" value="{{states.state_id}}" ng-selected="states.state_id == form.state_id"> {{states.name}} </option>
</select>
and in controller i have function as
$scope.getStateList = function(id) {
$http.post('/statelist',{id:id}).then(function success(response) {
$scope.state = response.data.state;
});
}
and i load $scope.city on load on different call. but when i load page both the functions get called as $scope.getStateList should be call on chnage in select box. Whats wrong ?
and one more problem is ng-select is not working too.
Change ng-model="states.state_id" ng-change="getStateList(states.state_id)" u want pass state id in ng-change event use this and try ..other wise u send whole scope values means send scope where u decalre in ng-repeat

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

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"

why select items are not being populated

Here is my html code
<select id="userGroups" name="userGroups" ng-model="userGroups" class="form-control">
<option value="{{grp.groupId}}" ng-repeat="grp in groups">{{grp.groupName}}</option>
</select>
here is my controller
function MyController($scope, MYAPI) {
$scope.groups = MYAPI.GroupList.get();
}
Why options are not being popuplated?
Ok I have changed my controller to resolve the GroupList before populating the view, but its still not showing
MYApp.controller('CreateUserController', ['$scope', 'groupList', function($scope, groupList) {
$scope.groups = groupList;
debugger; //here I can see groups has objects which I need to display
}]);
but still dropdown is not loading...
As Martin said you need to use ng-options.
This is how it should look like:
<select id="userGroups"
name="userGroups"
ng-model="userGroups"
ng-options="grp.groupId as grp.groupName for grp in groups"
class="form-control">
</select>
Accorting to the AngularJS documentation of select you have to use ng-options. This use case is not supported by ng-repeat:
ngOptions provides an iterator facility for the <option> element which should be used instead of ngRepeat when you want the select model to be bound to a non-string value. This is because an option element can only be bound to string values at present.

Resources