Unable to update value of Select from AngularJs - javascript

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];
});
});

Related

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.

ngModel not updated when ngOptions change

How can I prevent angular from updating the ngModel when the ngOptions array changes? Angular seems to set ngModel to null when the ngOptions array changed.
.controller('myController', function($scope) {
var vm = this;
vm.options = [];
vm.selected = null;
vm.getOptions = function(id) {
$http.get().done(function(response) {
vm.options = response.data;
});
};
}
say vm.selected = "1";
when vm.getOptions is called, the select options are being repopulated as expected, but angular seems to set vm.selected to null
How can I keep vm.selected = "1" after vm.options changes?
EDIT:
so I tried to set vm.selected after vm.options was set, however angular set vm.selected to null after my controller code runs.
so I tried to do:
$timeout(function(selected) {
vm.selected = selected;
}, 0, true, vm.selected);
this successfully sets vm.selected to the previous value, however the view isn't updated.
EDIT:
the html is:
<select name="myOption" ng-model="vm.selected"
ng-options="option.id as option.name for option in vm.options track by option.id">
<option value="">Select an option</option>
here is a plunkr to demonstrate. 1st, select an option, the click the update option button.
Be careful when using select as and track by in the same expression.
ngOptions
You're using the id as value for ngModel. you cannot track option.optionId on this. You should use the option instance instead:
<select ng-model="vm.selected"
ng-options="option as option.optionTitle for option in vm.options track by option.optionId">
<option value="">Select an option</option>
</select>
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
var vm = this;
vm.selected = null;
vm.options = [{optionId: 1, optionTitle: "one"}, {optionId: 2, optionTitle: "two"}];
vm.updateOptions = function() {
vm.options.push({optionId: 3, optionTitle: "three"});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<body ng-app="app" ng-controller="MainCtrl as vm">
<select ng-model="vm.selected" ng-options="option as option.optionTitle for option in vm.options track by option.optionId">
<option value="">Select an option</option>
</select>
<hr/>
vm.selected = {{ vm.selected }}
<br>
<button ng-click="vm.updateOptions()">Update Options</button>
<br>
</body>
Due to the numerous request for resetting the model on options change, Angular has made sure that the model value resets after the ng-options change for the versions > 1.4. However this will continue to work the same in the older versions of Angular.
Click here for the reference
In order to achieve the desired functionality, i would recommend you to use ng-repeat on options rather than ng-options on select.
<select ng-model="vm.selected">
<option value="">Select an option</option>
<option ng-repeat="option in vm.options track by option.optionId" value="{{option.optionId}}">{{option.optionTitle}}</option>
</select>
look at this plnkr example
hope this helps you!
This is one of such situation I got burnt myself due to not treating the model as object of the option and resorting to property of the selected option
How can I keep vm.selected = "1" after vm.options changes?
The vm.selected is a number not an object. It needs to be an object and must be the reference in the options
I made very small change to illustrate and get it to work.
First vm.selected treat it as object by following changes. Notice model is no longer optionId.
ng-options="option as option.optionTitle for option in vm.options track by option.optionId"
Second in the controller we are initializing the model as an object and a reference to the options.
vm.options = [{optionId: 1, optionTitle: "one"}, {optionId: 2, optionTitle: "two"}];
vm.selected = vm.options[1];
Also modified the plunkr for other changes related to optionId keeping unique. However those changes don't contribute to the point in question.

ng-repeat with options doesn't return object as value

I have a loop "ng-repeat" inside of
<select ng-model="something"></select>
so that each option in a list is rendered as an
<option>
inside of select block. My aim is to make "something" (which is a ng-model attached to select) to be equal to a selected object inside of the list. At this moment when I do "value="{{option}}" as a parameter of option, I have a JSON object as a String. But what I need is to get an object as an object. The code looks like this:
<select ng-model="something">
<option ng-repeat="option in list" value="{{option}}">{{option.name}}</option>
</select>
The thing I want is easily done by using ng-options, but I need to add additional "style" parameters depending on option.anotherField to each
<option>
You can use ng-value instead of value, which gives you the object you want:
<select ng-model="something">
<option ng-repeat="option in list" ng-value="option">{{option.name}}</option>
</select>
What about approach via temp proxy and it's relation with something variable with the help of ng-change($scope.setModel) directive:
(function(angular) {
'use strict';
angular.module('app', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [{name:'Tom',age:23},{name:'Max',age:33},{name:'Sam',age:43}];
$scope.something = $scope.list[0];
$scope.temp = $scope.something.name;
$scope.setModel = function(){
for(var item of $scope.list)
if(item.name == $scope.temp){
$scope.something = item;
break;
}
}
}]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller="ExampleController">
<select ng-change='setModel()' ng-model='temp'>
<option ng-repeat='option in list track by option.name' ng-attr-title='{{option.age}}'>{{option.name}}</option>
</select>
<div>something: {{something | json}}</div>
</div>

Angular select, ng-init with dynamic value

I'm trying to get a select box working in Angular. The problem I'm experiencing is to do with ng-init and setting it's default value from an object which is created during runtime. Heres my code:
<select
ng-model="settings.editing.panel.data.production_company"
ng-change="settings.editing.panel.data.production_company = selectValue"
ng-init="selectValue = settings.editing.panel.data.production_company"
>
<option
ng-repeat="(key, value) in lists.production_companies"
value="{{key}}"
ng-selected="{{selectValue}}"
>
{{value}}
</option>
</select>
"lists.production_companies" is a simple key-value array of names, populated during initial page render, updated by ajax.
The object "settings.editing.panel.data" starts its life as NULL, but later is loaded with a correctly formatted object which contains the property "production_company".
I have found setting ng-init to something like "ng-init="selectValue = 3" works fine. Setting a $scope.test = 3, then setting "ng-init="selectValue = test" works fine too.
However, my dynamic value does not work. How can I use my dynamically created object to set the value of this select box during runtime with the set-up I have?
<select
ng-model="settings.editing.panel.data.production_company"
ng-options = "option as option.keyName for option in list.production_companies"
> <!--set keyName equal to your object's key-->
</select>
Then in your controller
$scope.settings.editing.panel.data.production_company = list.production_companies[0] // Or which value you want to assign
You question confused me somehow. The following snippet is a working one, is that what you want?
'use strict';
angular.module('DemoApp', []);
angular.module('DemoApp').controller('DemoCtrl', ['$scope', function($scope){
$scope.lists={
production_companies: { "0": "prod 1", "1":"prod_2" },
};
$scope.settings={
editing: {
panel: {
data: null
}
}
};
$scope.setData=function(data){
$scope.settings.editing.panel.data={
production_company: data
};
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="DemoApp" ng-controller="DemoCtrl">
<select ng-model = "settings.editing.panel.data.production_company">
<option ng-repeat = "(key, value) in lists.production_companies" value = "{{key}}">{{value}}</option>
</select>
<div>You select: {{settings.editing.panel.data.production_company}}</div>
<button ng-click="setData('0')">Set Data to Prod1</button>
<button ng-click="setData('1')">Set Data to Prod2</button>
</div>
In my circumstances I was able to change my backends data format to set an object like:
{"id": 1, "name":"prod comp 1"}
and then change my select model accordingly. In hindsight I needed this for the ID anyway.
<select
ng-model="settings.editing.panel.data.production_company"
>
<option
ng-repeat="option in settings.lists.production_companies"
value="{{option.id}}"
ng-selected="{{option.id}} == settings.editing.panel.data.production_company"
>
{{option.name}}
</option>
</select>

multiple select setup causes error in angular

I want to simply select multiple options in a multiple select in AngularJS.
partial side :
<select name="usergroup"
ng-model="selected.data.split(',')"
ng-options="k as v for (k, v) in usergroup"
multiple>
</select>
and controller side :
$scope.selected = {data:"1,3"};
$scope.usergroup = {"1":"groupe 1","2":"groupe 2","3":"groupe 3"};
Here's the plunkr : i don't understand why i have all these js errors in the console, though the display is correct : the selected options are ok.
It seems from the error i can't use selected.data.split(',') but the selected data are ok.
This is a part of a "bigger" app, so :
the variables format are like this for a reason
$scope.selected isn't parsed (split) in the controller because, in the app, the selected data can be used untouched in other case (switch) which are not relevant here.
I would like to be able to parse the selected.data in the partial, is that possible ?
Thank you
The short answers is no, you cannot have the expression selected.data.split(',') as a ng-model attribute.
What you assign to ng-model must be a "Assignable angular expression to data-bind to".
If you have to use the provided selected.data string as an object you can use another temp variable for example $scope.userselected which then contains an array with the selected values.
<body ng-app="app" ng-controller="testController">
<select name="usergroup"
ng-model="userselected"
ng-options="k as v for (k, v) in usergroup"
multiple>
</select>
</body>
You can then add a $watch-listener to $scope.userselected and in the listener assign the correct value to selected.data:
app.controller('testController',['$scope', function($scope){
$scope.usergroup = {"1":"groupe 1","2":"groupe 2","3":"groupe 3"};
$scope.selected = {data:"1,3"}
$scope.userselected = ["1", "3"];
$scope.$watch('userselected', function(value) {
$scope.selected.data = value.join(',');
console.log($scope.selected.data);
});
}]);
Here is a working Plunker
Use ng-click inside your select-option, so whenever you select option value is pass to ng-click function.
and no need to use selected.data.split(',') in html. use this in Controller.
Here is working plunker
MarkUP
<select name="usergroup"
ng-model="selectedId"
ng-options="k as v for (k, v) in usergroup"
ng-click="selectedOption(selectedId)"
multiple>
</select>
Selected value : {{selected}}
Js
var app = angular.module('app',[]);
app.controller('testController',['$scope', function($scope){
// seleclted data
$scope.selected = {data:"1,3"};
// selected Ids
$scope.selectedId = $scope.selected.data.split(","); // pass selected ids
// userGroup
$scope.usergroup = {"1":"groupe 1","2":"groupe 2","3":"groupe 3"};
// ng-click function
$scope.selectedOption = function(data){
$scope.selected.data = data.toString();
}
}])
no need to watch manually, since ng-click is work as two-way-binding.

Categories