【问题标题】:Angularjs - Set default option in select with dynamic ng-modelAngularjs - 使用动态 ng-model 在选择中设置默认选项
【发布时间】:2018-01-12 14:09:43
【问题描述】:

我有这个问题:我在 ng-repeat 中创建了一个选择,每个选择的 ng-model 都是动态生成的。

我需要为这些选择设置一个默认值,但我不知道该怎么做

HTML

<div ng-controller="ricercaAttivita">
    <div class="accordion-group" ng-repeat="masterAttribute in masterAttributes">
        <select class="trip dark" ng-change = "search(1, true, true)" ng-model="masterAttribute.Id" ng-options="attr.Id as attr.Value for attr in masterAttribute.Values">
            <option value="">Tutte</option>
        </select>
    </div>
</div>

APP.JS

var tantoSvagoApp = angular.module('tantoSvagoApp');

tantoSvagoApp.controller("ricercaAttivita", function ($scope) {

    $scope.masterAttributes = {"id" : "11", nome" : "MARCHE", "values" :
                                                    [{ "id": "114", "nome": "ANCONA" }, { "id": "116", "nome": "ASCOLI PICENO" }]           
        },
                              {"id" : "12", nome" : "LOMBARDIA", "values" :
                                                    [{ "id": "120", "nome": "MILANO" }, { "id": "121", "nome": "BERGAMO" }]         
        };

});

我的选择的 ng-model 是“masterAttribute.Id”,我需要循环每个生成的选择,并在某些条件下设置一个特定的默认选项。

类似

$scope.masterAttribute.Id = 值;

我该怎么做? 任何人都可以帮帮我吗?

【问题讨论】:

    标签: angularjs angularjs-ng-model


    【解决方案1】:

    只需将选定的值对象设置为$scope.masterAttribute。在您的控制器中添加

    $scope.masterAttribute = masterAttribute.Values[0];
    

    希望这会有所帮助。

    【讨论】:

    • 在这种情况下,我有两个选择,一个带有 ng-model "masterAttribute.Id" = 11,另一个带有 "masterAttribute.Id" = 12。这样我如何设置一个值第一个选择和第二个选择的另一个值?
    【解决方案2】:

    $scope.masterAttributes 应该是一个数组 [],

     $scope.masterAttributes=[{
            "id": "11",
            nome " : "
            MARCHE ", "
            values " : [{
                "id": "114",
                "nome": "ANCONA"
            }, {
                "id": "116",
                "nome": "ASCOLI PICENO"
            }]
        },
        {
            "id": "12",
            nome " : "
            LOMBARDIA ", "
            values " : [{
                "id": "120",
                "nome": "MILANO"
            }, {
                "id": "121",
                "nome": "BERGAMO"
            }]
    

    最后在select中设置默认值是,

    $scope.masterAttribute = $scope.masterAttributes[0].values[0];
    

    【讨论】:

    • 我有两个选择,一个带有 ng-model "masterAttribute.Id" = 11,另一个带有 "masterAttribute.Id" = 12。这样我如何为第一个选择设置一个值以及循环内第二个选择的另一个值?
    猜你喜欢
    • 2014-02-16
    • 2016-03-19
    • 2014-07-26
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 2017-12-11
    相关资源
    最近更新 更多