-1

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.

Ahmad.Masood
  • 1,289
  • 3
  • 21
  • 40
  • possible duplicate of [Working with select using Angular's ng-options](http://stackoverflow.com/questions/13047923/working-with-select-using-angulars-ng-options) – Julien Jun 02 '14 at 09:15
  • I am unable to update it from javascript. Thats my main problem. – Ahmad.Masood Jun 02 '14 at 09:20

3 Answers3

1

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.

1st4ck
  • 1,267
  • 11
  • 11
0

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" } 
})
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

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];
  });
});
guru
  • 4,002
  • 1
  • 28
  • 33