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.
In my case ng-model
was not updating because my select
is inside an element with ng-if
.
<div class="editor-panel" ng-if="editorEnabled">
...
<select ng-options="item as item.description for item in items" ng-model="selectedItem"/>
...
</div>
ng-if
creates another scope and ng-model
refers to a variable in this child scope rather than the intended variable.
To fix the issue I changed ng-model="selectedItem"
value to ng-model="$parent.selectedItem
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>
try this
<div ng-controller="MyCtrl">
<select data-ng-model="period" ng-options="item.value as item.text for item in periodOptions"></select>
<span>period value=, {{period}}!</span>
</div>
The code for select and ngOptions
is correct. However I assume that you want $scope.Search
function to be called on every option change. In this case you need to set up ngChange
handler:
<select ng-model="period"
ng-options="item.value as item.text for item in periodOptions"
ng-change="Search()">
</select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.