【问题标题】:Unable to Set Selected Value Of DropDown In angularJs无法在angularJs中设置下拉菜单的选定值
【发布时间】:2015-03-26 00:22:27
【问题描述】:

我有一个下拉菜单。我在 Option 上使用ng-repeat 绑定它的值。 我只想使用值字段设置选定的值。

这是我的代码。

<div ng-controller="myCtrl">
    <select ng-model="selectedItemvalue">
        <option value="">--Select --</option>
        <option ng-repeat="sel in selectables" value="{{sel.value}}">{{sel.label}}</option>
    </select>
    <p>Selected Value is : {{selectedItemvalue}}</p>
</div>

JS

angular.module('myApp', [])

// controller here
.controller('myCtrl', function($scope) {
    $scope.selectables = [
        { label: 'A', value: 1},
        { label:'B', value: 2},
        { label: 'C', value: 3}
    ];

    // this is the model that's used for the data binding in the select directive
    // the default selected item
    //using value, i want to set the selected value
    $scope.selectedItemvalue = "2"; 
})

My Fiddle

如您所见,我只想通过设置值来设置选定的值。

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    您需要使用ng-model 而不是ng-value 将其绑定到模型。

    <select ng-model="selectedItemvalue">
    

    更新: $scope.selectedItem 需要在控制器中为 $scope.selectedItemvalue 然后你可以使用 ng-selected 来匹配它的条件

    工作演示

    angular
    .module('myApp', [])
    
    // controller here
    .controller('myCtrl', function($scope) {
        $scope.selectables = [
            { label: 'A', value: 1},
            { label:'B', value: 2},
            { label: 'C', value: 3}
        ];
    
        // this is the model that's used for the data binding in the select directive
        // the default selected item
        //using value, i want to set the selected value
        $scope.selectedItemvalue = "2"; 
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
    <div ng-controller="myCtrl" ng-app="myApp">
        <select ng-model="selectedItemvalue">
            <option value="">--Select --</option>
            <option ng-repeat="sel in selectables" ng-selected="selectedItemvalue == sel.value" value="{{sel.value}}">{{sel.label}}</option>
        </select>
     <p>Selected Value is : {{selectedItemvalue}}</p>
    </div>

    【讨论】:

    • 查看更新的链接。还是一样的问题
    • 但最初,您的 Demo 中没有选择第二个 Itme,
    • 您希望最初选择第二个项目吗?
    • @AmitKumar 立即查看答案和演示
    • @AB:是的。它可以是任何项目。就像如果我设置 $scope.selectedItemvalue = "3"; 那么它将设置选定的项目,其提交的值为 3
    【解决方案2】:

    如果你尝试

    $scope.selectedItemvalue = { label:'B', value: 2};

    然后它会工作。

    【讨论】:

    • 嗨。不,我想创建对象来设置选定值。我只想使用 Value 字段进行设置。
    • 然后试试
    【解决方案3】:

    您的option 标签基本上需要使用以下语法(使用ng-selected):

    <option ng-repeat="sel in selectables" value="{{sel.value}}" ng-selected="sel.value == selectedItemvalue">{{sel.label}}</option>
    

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 2014-04-27
      • 2011-06-17
      • 2016-07-09
      相关资源
      最近更新 更多