Why ng-model does not update controller value select?

23,287

Solution 1

To get updated or change value inside your controller, you could write ng-change function on it. Then you could check the updated value inside controller.

Markup

<select ng-model="selectedItem" ng-options="item.name for item in items"
  ng-change="changeSelectedItem()">
</select>

Code

$scope.changeSelectedItem = function(){
   console.log($scope.selectedItem);
}

Other way could be you could simply use {{selectedItem}} on html somewhere. That will also give an idea about how selectedItem value is updating.

Solution 2

Because you are always taking the first item of the array in the controller,

$scope.selectedItem = $scope.items[0];
console.log($scope.selectedItem);

Just change your JS like this,

$scope.changeSelectedItem = function(){
   console.log($scope.selectedItem);
}

And the View use the ng-change to get the selected item

<select ng-model="selectedItem" ng-options="item.name for item in items"
  ng-change="changeSelectedItem()">
</select>
Share:
23,287
alvarezsh
Author by

alvarezsh

Updated on July 12, 2022

Comments

  • alvarezsh
    alvarezsh almost 2 years

    This is the code HTML:

    <div ng-controller="SelectCtrl">
        <p>selected item is : {{selectedItem}}</p>
        <p> age of selected item is : {{selectedItem.age}} </p>
        <select ng-model="selectedItem" ng-options="item.name for item in items">
        </select>
    </div>
    

    This is the code AngularJS:

    var app = angular.module('myApp', []);
    
    app.controller('SelectCtrl', function($scope) {
        $scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
        $scope.selectedItem = $scope.items[0];
        console.log($scope.selectedItem); //it's not update :(
    });
    

    in the view the new value updated every time I change the select, but the controller does not update the current value of the select. What should I do?

    Thanks!

  • Sajeetharan
    Sajeetharan almost 9 years
    hmm true it happens :)
  • Pankaj Parkar
    Pankaj Parkar almost 9 years
    @VirajNalawade You should go for it..Thanks for appreciation.. :)
  • Sajeetharan
    Sajeetharan almost 9 years
    @alvarezsh please mark as an answer if it has helped