更新与NG-选项和模式NG-选择选项、模式、NG

2023-09-13 05:06:55 作者:上岸撒尿的鱼

我试图用NG选项更新从下拉菜单中选择一个模型,并利用采摘NG-选择已经选择的值。这里有一个简单的例子(和小提琴)。

I'm trying to update a model from a drop down menu using ng-options, and picking the already selected value using ng-selected. Here's a simplified example (and fiddle).

HTML

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="QuarterController">
    <select name="quarter" ng-model="Quarter.id" ng-options="q.id as q.val for q in Quarters">
      <option ng-selected="Quarter.val===q.val"></option>
    </select>
    <input type="button" name="Submit" value="Submit" ng-click="submit()"/>
    <br/>
    <p>{{answer}}</p>
  </div>
</div>

function QuarterController($scope) {
    $scope.Quarters = [{val: 'Q1', id: 1}, {val: 'Q2', id:2}, {val:'Q3', id:3}, {val:'Q4', id:4}];
    $scope.Quarter = {val: 'Q2', id: 2, extraField: 'Hello'};

    $scope.submit = function() {
        $scope.answer = "Val: " + $scope.Quarter.val + ", Id: " + $scope.Quarter.id + $scope.Quarter.extraField;
    };
}

那么,什么是怎么回事是下拉选项是VALS从$ scope.Quarters,与所选择的选项的ID被保存在$ scope.Quarter.id。 提交显示从$ scope.Quarter id和VAL。在提交$ scope.Quarter.id更新,但并不是$ scope.Quarter.val。任何人都知道如何做到这一点?

So what's going on here is the drop-down options are the "val"s from $scope.Quarters, with the selected option's id being saved in $scope.Quarter.id. "submit" displays the id and val from $scope.Quarter. $scope.Quarter.id updates on submit, but not $scope.Quarter.val. Anybody know how to accomplish this?

修改

$ scope.Quarter.extraField更好地说明我试图解决这个问题。我需要身份证和Val更新,但我想extraField保持不变。

$scope.Quarter.extraField was added to better illustrate the problem I'm trying to solve. I need id and val to update, but I want extraField to stay the same.

推荐答案

您已经有了小错误Inn的选择指令,请参阅的这里

You've got small error inn your select directive please see here

查看:          

待办事项

  <div ng-controller="QuarterController">
    <select name="quarter" ng-model="Quarter" ng-options="q.val for q in Quarters">
        <option value="">{{Quarter.val}}</option>
    </select>
      <input type="button" name="Submit" value="Submit" ng-click="submit()"/>
      <br/>
      <p>{{answer}}</p>

  </div>
</div>

JS:

function QuarterController($scope) {
    $scope.Quarters = [{
        val: 'Q1',
        id: 1
    }, {
        val: 'Q2',
        id: 2
    }, {
        val: 'Q3',
        id: 3
    }, {
        val: 'Q4',
        id: 4
    }];
    $scope.Quarter = {
        val: 'Q2',
        id: 2
    };

    $scope.submit = function () {
        $scope.answer = "Val: " + $scope.Quarter.val + ", Id: " + $scope.Quarter.id;
    };
}