Unfortunately I'm just going round in circle trying to work this out - any help would be really appreciated.
I would like to update the model and selected option of a select that is generated using ng-options.
Here are the values for the options:
var blahOptionValues = [
{valueForModel: '1', optionText: 'a'},
{valueForModel: '2', optionText: 'b'},
{valueForModel: '3', optionText: 'c'},
]
Here is my view:
<select ng-model="blahModel" ng-options="item.valueForModel as item.optionText for item in blahOptionValues"></select>
As a result of another event, how would I update the "blahModel" with the relevant value? Would this also update the selected value in the view as well?
You need to select the same reference in order to show a value in the select.
That is, if you wish to set the blahModel based on an event, you need to do the following:
//Assume that the following code is in your event handler.
//Assuming here that you want to set the value of the select to 'b'
$scope.blahModel = $scope.blahOptionValues[1].valueForModel
If you directly set the value to 2
it will not work since it is not the same reference. You need to explicitly use the same iterator as the one used in ng-repeat
. Also, there seems to be a bug in your code - blahOptionValues should be on the scope and not as a local variable.
With reference from "As a result of another event, how would I update the "blahModel" with the relevant value"
I am extending your code. I have one textbox in which you will enter values either 1,2 or 3 and click in set button and select value is updated.
I have added track by in ng-options.
Html :-
<select ng-model="blahModel" ng-options="item.valueForModel as item.optionText for item in blahOptionValues track by item.valueForModel"></select>
<input type="text" data-ng-model="searchSelect"/>
<input type="button" data-ng-click="SetSelect()" value="Set"/>
Angular Code :-
$scope.SetSelect = function () {
$scope.blahModel={valueForModel:$scope.searchSelect};;
};
Yes, it will update the view as well. Please check the demo in plunker: link: http://plnkr.co/edit/7XVrn7GmfKrJS7e4fvuH?p=preview `
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.blahOptionValues = [ {valueForModel: '1', optionText: 'a'}, {valueForModel: '2', optionText: 'b'}, {valueForModel: '3', optionText: 'c'}, ]; $scope.blahModel = '2'; $scope.update = function(){ $scope.blahModel = '1'; }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl">{{blahModel}} <select ng-model="blahModel" ng-options="item.valueForModel as item.optionText for item in blahOptionValues"></select> <button ng-click="update()" >update</button> </div>
`
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.