【问题标题】:$scope not picking up ng-model value in select element$scope 没有在选择元素中获取 ng-model 值
【发布时间】:2016-03-02 00:40:29
【问题描述】:

我正在尝试向从 ng-model 接收它的变量添加一个值。

这里是 HTML:

<div ng-form="amountForm" class="form-group" id="inputField">
    <input value="1" type="number" placeholder="1" ng-model="itemAmount" ng-maxlength="2" required>
</div>
<div ng-form="nameForm" class="form-group">
    <input value="" type="text" placeholder="Name of Item" ng-model="itemName" ng-maxlength="10" required>
</div>
<select ng-model="currentDependent">
    <option ng-repeat="item in items" value="{{item.dependentOn}}" ng-selected="currentDependent == item.dependentOn">{{item.name}}</option>
</select>

这是 Angular($scope.itemAmount 和 $scope.itemName 有效):

$scope.items = [];

$scope.addItem = function () {
    console.log($scope.itemAmount + ", " + $scope.itemName + ", " + $scope.currentDependent);

    $scope.items.push({
        amount: $scope.itemAmount,
        name: $scope.itemName,
        showMe: false,
        dependentOn: $scope.currentDependent
    });
};

控制台上似乎没有打印任何内容:

所以唯一不起作用的是 Select 中的 ng-model。下拉列表显示正确的值。如何获取在下拉列表中选择的值以在控制台中打印?

注意:为了清楚起见,我省略了 http.post 代码。

【问题讨论】:

  • 尝试使用字典。即 ng-model 的 item.itemname。

标签: angularjs data-binding angular-ngmodel angularjs-select


【解决方案1】:

您应该使用 itemName(或其他项目属性)来跟踪依赖关系。

<select ng-model="currentDependent">
    <option ng-repeat="item in items" value="{{item.name}}">{{item.name}}</option>
</select>

【讨论】:

    【解决方案2】:

    最近我不得不在我的一个项目中使用下拉菜单,这就是我个人的做法

    http://jsfiddle.net/halirgb/Lvc0u55v/

    别忘了打开控制台查看数值!

    起初,我认为只使用ng-repeat 我的选项是个好主意。但后来我发现,当你掌握了窍门后,使用ng-options 会更方便。

    This SO question 解释得很好!

    【讨论】:

    • 谢谢,使用 ng-options 是下拉列表的更好选择。但它似乎与 ng-repeat 配合得很好。
    猜你喜欢
    • 2016-06-12
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2013-05-14
    相关资源
    最近更新 更多