我无法更新AngularJs中的select值。
这是我的代码
<select ng-model="family.grade" >
<option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option>
</select>
以下是我用来填充选择
的选项var options = [{text:'Pre-K',id:'Pre-K'},
{text:'K',id:'K'},
{text:'1',id:'1'},
{text:'2',id:'2'},
{text:'3',id:'3'},
{text:'4',id:'4'},
{text:'5',id:'5'},
{text:'6',id:'6'},
{text:'7',id:'7'},
{text:'8',id:'8'},
{text:'+',id:'+'}];
这是mu js代码。
$scope.$watch("family_member.date_of_birth" ,function(newValue, oldValue){
$scope.family.grade = "1"
})
当family_member.date_of_birth的值发生变化时,应将select的值设置为1.但此更改在UI上不可见。
答案 0 :(得分:1)
您应该使用ngSelected选择选项。
它可能是这样的:
<select ng-model="family.grade" >
<option ng-repeat="option in options"
value='{{option.id}}' ng-selected="family.grade==option.id">
{{option.text}}</option>
</select>
希望这有帮助。
答案 1 :(得分:0)
我认为您正在寻找track by
的{{1}}条款:
ng-options
但是,您仍需要提供具有<option ng-repeat="option in options track by option.id">{{option.text}}</option>
属性的对象来设置:
id
答案 2 :(得分:0)
选项数组个别元素是对象。因此,相应的ng模型也需要成为一个对象。因此,即使在js中进行更改,也必须提供相应的对象而不是字符串。 示例演示:http://plnkr.co/edit/naYcnID29SPa90co0leB?p=preview
HTML: JS: var app = angular.module('plunker',[]);
app.controller('MainCtrl',function($ scope){
$scope.options = [{text:'Pre-K',id:'Pre-K'},
{text:'K',id:'K'},
{text:'1',id:'1'},
{text:'2',id:'2'},
{text:'3',id:'3'},
{text:'4',id:'4'},
{text:'5',id:'5'},
{text:'6',id:'6'},
{text:'7',id:'7'},
{text:'8',id:'8'},
{text:'+',id:'+'}];
$scope.family = {};
$scope.family_member = {
date_of_birth: '10-Jan-1986'
};
$scope.$watch("family_member.date_of_birth", function(newValue, oldValue) {
$scope.family.grade = $scope.options[2];
});
});