Set Selected Option In Dropdown in AngularJS onload - javascript

In Angularjs, I have a DropDown:
<select ng-model="category" ng-change="categoryChanged(category)" class="form-control"
data-ng-options="category as category.name for category in categories">
<option value="">Select Category</option>
</select>
And I have a controller:
app.controller('searchBoxController', ['$scope', '$location', '$routeParams', 'categoryService', function ($scope, $location, $routeParams, categoryService) {
categoryService.getParentCategory().$promise.then(
function (model) {
$scope.categories = model;
$scope.category.id = $routeParams.categoryId;// Which is coming as "1"
},
function (error) {
});
$scope.categoryChanged = function (category) {
alert(category.id);
};
}]);
$routeParams.categoryId is coming as "1" but still it is not setting the selected option in the dropdown.

Your categories variable is an array of objects, while you set the ng-model to an object with only an id. Because it is a whole new object, angular doesn't see it as a match of the category in your array, and won't select the correct one.
The solution is to set the $scope.category to the matching object of the array instead of creating a new one:
var id = $routeParams.categoryId;
// Find the category object with the given id and set it as the selected category
for (var i = 0; i < $scope.categories.length; i++){
if ($scope.categories[i].id == id) {
$scope.category = $scope.categories[i];
}
}

You have to change ng-model directive when promise operation is end.
<select ng-model="category" ng-change="categoryChanged(category)" class="form-control" data-ng-options="category as category.name for category in categories">
<option value="">Select Category</option>
</select>
Suppose you have var id = $routeParams.categoryId and its value is 2 for example. You have to find category from categories where category.id is 2. For this, the simpliest method is to use a filter method.
$scope.category = $scope.categories.filter(function(item){
return item.id==$scope.id;
})[0];
Please take a look to working fiddle

Related

ng-options creates new instance of model instead of getting one from the datasource

Does ng-options clone objects and if that is the case is there some way to stop it?
in the following code:
html:
<div ng-controller="Main">
<select ng-options="item as item.text for item in items track by item.id" ng-model="item">
<option value="">select something else</option>
</select>
<button ng-click="test()">
test
</button>
</div>
javascript:
angular
.module('myApp', [])
.controller('Main', function($scope) {
const Test = function(id, text) {
this.id = id;
this.text = text;
}
$scope.items = [new Test('1', 'test1'), new Test('2', 'test2')];
$scope.item = null;
$scope.test = function() {
if (!$scope.items.includes($scope.item) && $scope.item !== null) {
alert("Items should contain item?")
debugger;
}
}
});
http://jsfiddle.net/p0a918n4/
Select a item in the drop down an click the button.
The alert should not happen, but for some reason the $scope.item variable seems to be a clone and not the exact same reference? (Does ng-options + track by some how clone the object and create a new instance?)
If you select the first item and use a debugger and write $scope.items[0] === $scope.item it results in false?

AngularJS changing dropdown value with ng-model

nameList contains [“Julia”, “Evan”, “Tomas”];
select ng-model=“names” ng-options=“x for x in nameList”
In controller, I have a service api call GetNameByID/{id}”and depending on the id, I want to initialize the dropdown value of the modal form.
So if the user clicks ID 1, the dropdown defaults to Julia.
The problem is within the service call, when I try to initialize the model by doing $scope.names = data, it adds an empty option at the top instead of selecting Julia. When I console.log(data), it prints “Julia” but it becomes <option value=“?”></option>
How can i fix this?
So Lets have a HTML example for this case:
<div ng-app ng-controller="MyCtrl">
<select ng-model="names" ng-options="item for item in nameList">
</select>
<p>Selected : {{names}}</p>
<button ng-click="Update(2)"> Update(1)</button>
</div>
and Conrtoller has one service call which update your dropdown accordingly based on index.
function MyCtrl($scope) {
$scope.names = "Julia"
$scope.nameList = ["Julia", "Evan", "Tomas"];
$scope.Update = function(_value){
$scope.names = $scope.nameList[ parseInt(_value)] ;
}
}
Please have a look into running code, jsfiddle.
You can just use ng-init to initialize the dropdown first value like so:
<select ng-model="names" ng-init="names = data[0]" ng-options="x for x in data">
<option value="">Select</option>
</select>
Where [0] in data[0] is the position of the array.
Here is an example where you can set the option
In html file
<select ng-model="selectedName" ng-options="x for x in nameList"></select>
In js file
app.controller('myCtrl', function($scope) {
var id = 1;
$scope.names = ["Julia", "Evan", "Tomas"];
$scope.selectedName = $scope.names[id-1]; <---- here you can pass you id.
});
subtract id with 1 because array start with 0. Hope this is what you want to acheive.

how to select few json values in drop down in angularjs

i am getting a data from json file and the values using in dropdown but i dont want to use all values,I want to select only three values in my dropdown.
You can filter the list at the time of feeding it to the dropdown.
<select ng-model="toType" class="form-control" required ng-change="ConvertCurrency()"
ng-options="k for (k, v) in (rates | 'yourfilter') track by v"></select>
[UPDATE]
I tried to access the API, and found out that res.data.rates is an object and not an array.
So if you only have to show these 3 values, the easy approach would be to create a new array in controller:
var ratesToDisplay = [];
ratesToDisplay.push({rate:'USD', value: res.data.rates.USD});
ratesToDisplay.push({rate:'EUR', value: res.data.rates.EUR});
ratesToDisplay.push({rate:'CAD', value: res.data.rates.CAD});
and feed this new filtered array to your dropdown.
<select ng-model="selectedRate" ng-options="rate.value as rate.rate for rate in ratesToDisplay">
<option value="" disabled>Please Select</option>
</select>
I hope this helps.
For 2nd part of your problem
You can implement the ng-change() method and call the API from that method. Ex:
function onDDChange(){
$http.get('http://api.fixer.io/latest?' + $scope.fromType.label)
.then(function(res) { \\logic for success call back
\\ call convert currency method from here.
});
}
HTML:
<select ng-model="fromType" class="form-control" required
ng-change="onDDChange()" ng-options="f as f.label for f in rates">
I have written this code and it is working for me
angular.module('CurrencyConv', [' ']).controller('ConvertCtrl', ['$scope', '$http', function($scope, $http) {
$scope.rates = [];
$scope.toType = {};
$scope.fromType = {};
$http.get('http://api.fixer.io/latest?base').then(function(res) {
$scope.fromValue = 1;
$scope.ConvertCurrency();
var i = 0;
angular.forEach(res.data.rates, function(value, key) {
if (key == "USD" || key == "EUR" || key == "CAD") {
$scope.rates.push({ value: value, label: key });
// $scope.toType = $scope.rates.CAD;
// $scope.fromType = $scope.rates.USD;
}
i++;
});
});
<select ng-model="fromType" class="form-control" required ng-change="ConvertCurrency()" ng-options="f as f.label for f in rates">

How to bind both the option's value and text in a drop down list using Angular.JS

In Angular.JS, is there a way to bind two different ng-models when a select drop down option is selected?
Angular code:
<select ng-model="vm.data.styleId" ng-options="item.id as item.name for item in vm.getStylesData.styles">
<option value="">Select a Style</option>
</select>
Results in:
<option value="{{item.id}}">{{item.name}}</option>
With the Angular code I have so far, when an option is selected, it will save the option's value to the ng-model. In this case item.id is bound to vm.data.styleId.
However in addition to this, I also need to bind the 'item.name' of the selected option. Basically, when an option is selected, I need to bind both the item.id to vm.data.styleId, and the item.name to vm.data.name.
Is there an easy way to do this using Angular.JS?
Solution (using the answer from lisa p.):
In the View:
<select ng-model="vm.styleItem" ng-change="vm.getDetails()" ng-options="item as item.name for item in vm.getStylesData.styles">
<option value="">Select a Style</option>
</select>
Inside the controller:
vm.getDetails = function () {
// set the values of the select drop down
vm.data.styleId = vm.styleItem.id;
vm.data.style = vm.styleItem.name;
}
You can bind to an object containing both values like
item = { styleId: 23, name: "the name" }
vm.data = {{ styleId: ..., name: ... }}
then you bind to vm.data with
<option value="{{item}}">{{item.name}}</option>
Controller
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.vm.data.styleId = "";
$scope.item = {id : '1', name : 'name'};
});
html
<div ng-controller="myCtrl">
<select ng-model="vm.data.styleId" ng-options="item.id as item.name for item in vm.getStylesData.styles">
<option value="{{item}}">{{item.name}}</option>
</select>
</div>
Make an object which holds both id and name and pass that object as value to option

Unable to update value of Select from AngularJs

I am unable to update value of select from AngularJs.
Here is my code
<select ng-model="family.grade" >
<option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option>
</select>
Here are the options which i am using to populate my select
var options = [{text:'Pre-K',id:'Pre-K'},
{text:'K',id:'K'},
{text:'1',id:'1'},
{text:'2',id:'2'},
{text:'3',id:'3'},
{text:'4',id:'4'},
{text:'5',id:'5'},
{text:'6',id:'6'},
{text:'7',id:'7'},
{text:'8',id:'8'},
{text:'+',id:'+'}];
Here is mu js code.
$scope.$watch("family_member.date_of_birth" ,function(newValue, oldValue){
$scope.family.grade = "1"
})
When ever value of family_member.date_of_birth changes it should set they value of select to 1. But this change is not visible on UI.
You should use ngSelected to select the option.
it could be something like this:
<select ng-model="family.grade" >
<option ng-repeat="option in options"
value='{{option.id}}' ng-selected="family.grade==option.id">
{{option.text}}</option>
</select>
Hope this helps.
I think you are looking for the track by clause of ng-options:
<option ng-repeat="option in options track by option.id">{{option.text}}</option>
However, you will still need to supply an object with an id property to set:
$scope.$watch("family_member.date_of_birth" ,function(newValue, oldValue){
$scope.family.grade = { id: "1" }
})
The options array indiviual elements are objects. So the respective ng-model also need to be an object. So even when it is being changed in js, the respective object has to be provided rather than a string.
Sample demo: http://plnkr.co/edit/naYcnID29SPa90co0leB?p=preview
HTML:
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.options = [{text:'Pre-K',id:'Pre-K'},
{text:'K',id:'K'},
{text:'1',id:'1'},
{text:'2',id:'2'},
{text:'3',id:'3'},
{text:'4',id:'4'},
{text:'5',id:'5'},
{text:'6',id:'6'},
{text:'7',id:'7'},
{text:'8',id:'8'},
{text:'+',id:'+'}];
$scope.family = {};
$scope.family_member = {
date_of_birth: '10-Jan-1986'
};
$scope.$watch("family_member.date_of_birth", function(newValue, oldValue) {
$scope.family.grade = $scope.options[2];
});
});

Categories