无法从AngularJs中更新Select的值

Unable to update value of Select from AngularJs

本文关键字:更新 Select 的值 AngularJs      更新时间:2023-09-26

我无法从AngularJs中更新select的值。

我的代码

      <select ng-model="family.grade" >
         <option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option>
      </select>
下面是我用来填充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" 
})

When ever value of family_member。Date_of_birth更改它应该将select的值设置为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>

我想你是在找ng-optionstrack by条款:

<option ng-repeat="option in options track by option.id">{{option.text}}</option>

但是,您仍然需要提供一个具有id属性的对象来设置:

$scope.$watch("family_member.date_of_birth" ,function(newValue, oldValue){
    $scope.family.grade = { id: "1" } 
})

选项数组的各个元素都是对象。所以相应的ng模型也需要是一个对象。因此,即使在js中进行更改,也必须提供相应的对象而不是字符串。示例演示:http://plnkr.co/edit/naYcnID29SPa90co0leB?p=preview

HTML:JS:Var app = angular。模块("恰好",[]);

应用程序。控制器('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];
  });
});