【问题标题】:Angularjs include an empty option in html select using ng-repeat - Umbraco back end with Angularjs 1.1.5Angularjs 使用 ng-repeat 在 html 选择中包含一个空选项 - Umbraco 后端与 Angularjs 1.1.5
【发布时间】:2016-02-25 08:38:08
【问题描述】:

正如标题所说,当我使用ng-repeat 而不是ng-options 时,我的HTML 中出现了一个空选项。我使用 ng-repeat 而不是 ng-options 的原因是能够根据每个选项的值设置一个类。我尝试使用带有 ng-options 的指令,但没有达到预期的结果。问题不在于未设置默认选定值,正如您从生成的 HTML 中看到的那样。我怀疑空选项来自 select ng-model 但我不确定。

我的 HTML 如下所示:

        <select ng-model="selectedProduct.code" ng-init="selectFirstProduct()" ng-change="getArticle()" size="8">
            <option ng-selected="{{product.code == selectedProduct.code}}" ng-repeat="product in productsForPriceList" ng-class="getClassForProduct(product )" value="{{product.code}}">{{product.name}}</option>
        </select>

这导致 HTML 看起来像这样:

<select ng-model="selectedProduct.code" ng-change="getArticle()" size="8" class="ng-pristine ng-valid">
<option value="? string:200230 ?"></option>
<!-- ngRepeat: product in productsForPriceList -->
<option ng-selected="true" ng-repeat="product in productsForPriceList" ng-class="getClassForProduct(product)" value="200230" class="ng-scope ng-binding" selected="selected">Product 1</option>
<option ng-selected="false" ng-repeat="product in productsForPriceList" ng-class="getClassForProduct(product)" value="300025" class="ng-scope ng-binding">Product 2</option>
<option ng-selected="false" ng-repeat="product in productsForPriceList" ng-class="getClassForProduct(product)" value="300206" class="ng-scope ng-binding">Product 3</option>

我使用ng-init="selectFirstProduct()"selectedProduct.code 设置为列表中的第一个值。但是,如果我在获取列表时省略此代码并设置 selectedProduct.code ,结果仍然相同。

我正在使用 Umbraco 7.3.5 版后端和 Angularjs 1.1.5 版。

【问题讨论】:

    标签: javascript html angularjs umbraco


    【解决方案1】:

    初始化selectedProduct.code,它将从列表中删除空白选项。

    初始化对象

    $scope.selectedProduct = {};
    

    将 A 默认设置为列表

    $scope.productsForPriceList.YourObjectKey.IsDefault = true;
    

    将此行代码添加到 Controller 以初始化您的选项

    $scope.selectedProduct.code = $filter('filter')($scope.productsForPriceList, {IsDefault: true})[0];
    

    需要在控制器中添加依赖$filter

    【讨论】:

    • 不幸的是,这个解决方案对我不起作用。 $scope.productsForPriceList 也是动态的,因此即使我认为第一次运行,您的代码也很容易出错。
    猜你喜欢
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 2012-09-21
    • 2017-05-21
    • 2016-12-11
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多