Besa Besa - 1 year ago 36
AngularJS Question

How to update the ng-model when using ng-options in Angularjs?

I cant make my model to be updated when I select an option.

Here is my view:

<select data-ng-model="period" ng-options="item.value as item.text for item in periodOptions"></select>


And in my controller.js I have the following :

$scope.periodOptions = [
{ text: "This week", value: 'week' },
{ text:"This month", value: 'month '},
{ text:"This year", value: 'year' },
{ text:"All times", value: 'all-time '}
];

$scope.Search = function () {

return $http({
url: '/api/get',
method: 'GET',
params: {
period: $scope.period
}
}).then(function(response) {
console.log(response);
}, function(reason) {
alert(reason);
});
};


The $scope.period does not take the value of the option that is chosen from the User. I spent many hours on this and can't figure it out why is this happening.

Answer Source

Below is a solution which should work (Notice a minor change to your existing code use ng-options="item as item.text ... instead of ng-options="item.value as item.text). Hope this helps!

var myCtrl = function($scope){
  
  $scope.periodOptions = [
            { text: "This week", value: 'week' },
            { text:"This month", value: 'month '},
            { text:"This year",  value: 'year' }, 
            { text:"All times",  value: 'all-time '}
        ];
  
$scope.Search = function () {
alert('will call api with period: '+$scope.period.text);
  /*
            return $http({
                url: '/api/get',
                method: 'GET',
                params: {
                    period: $scope.period
                }
            }).then(function(response) {
                console.log(response);
            }, function(reason) {
                alert(reason);
            });
            */
        };
  
  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="myCtrl">
<select data-ng-model="period" ng-options="item as item.text for item in periodOptions" ng-change="updatePeriod()"></select>
  <div>{{period}} </div>
  <button ng-click='Search()' >Search</button>
  </div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download