selected item is : {{s...">

Why doesn't the ng model update the controller value selection?

This is the HTML code:

<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 AngularJS code:

 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 not update :( }); 

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

Thanks!

+5
source share
2 answers

To update or change a value inside your controller, you can write the ng-change function on it. Then you can check the updated value inside the 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); } 

Another way, maybe you can just use {{selectedItem}} in the html somewhere. It will also give an idea of ​​how the selectedItem value is updated.

+9
source

Since you always take the first element of an array in the controller,

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

Just change the js this way

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

And in the view use ng-change to get the highlighted item

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

All Articles