【问题标题】:Setting value in select dropdown which is populating by ng-repeat在由 ng-repeat 填充的选择下拉列表中设置值
【发布时间】:2016-10-21 00:11:23
【问题描述】:

我有一个数组如下:

hunting_lands = {"1":{"name":"forest and rivers"},"2":{"name":"safari"},"3":{"name":"sea"},"4":{"name":"Mountains"}} 

我有一个选择下拉列表,我在上面使用 json:

   <select  id="favourite_hunting_land">
       <option value ="[[key]]" ng-repeat="(key, value) in hunting_lands">[[value.name]]</option>
   </select>

现在我想显示一个选择的值,例如 sea

为此我尝试过: 我设置了狩猎土地下拉菜单 ng-model = fav_hunting_land

$scope.$watch('fav_hunting_land', function() {
        $scope.fav_hunting_land = 3;
    });

但是我有其他 onchange 函数不起作用,选择下拉列表也不起作用,即我无法更改值。 它工作并显示选择了 3 个值。

所有想要的只是在使用 ng-repeat 填充的选择下拉列表中显示选定的值。

更新

我将 [[]] 用于使用插值的表达式。

【问题讨论】:

    标签: angularjs ng-repeat angularjs-digest


    【解决方案1】:

    在 HTML 中使用它

    <select id="favourite_hunting_land" ng-model="selectedItem"> <option value ="{{item.name}}" ng-repeat="item in hunting_lands">{{item.name}}</option> </select> <br> Value selected is {{selectedItem}}

    【讨论】:

    • 这会给我一个值,我想设置一个值。你在告诉我如何获得价值。
    • 这还将设置(显示)动态填充下拉列表中的值。我在选择标签中添加了ng-model="selectedItem"。尝试运行它。
    【解决方案2】:

    使用表达式

    <select  id="favourite_hunting_land">
           <option value ="key" ng-repeat="(key, value) in hunting_lands">{{value.name}}</option>
    </select>
    

    编辑:

    您可以使用 ng-init 设置初始值

       <select ng-init="selected='3'" ng-model="selected " ng-options="c.key as c.value for c in hunting_lands"></select>
    

    DEMO

    【讨论】:

    • 我已经更新了我的问题。我使用 [[]] 括号表示使用插值的表达式。
    • 检查插件
    • 我想设置一个特定的值
    • @Simer 的价值是什么?
    • 值为 3。它可以是我提到的数组中的任何值。
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多