簡體   English   中英

動態形式的唯一標識符(ng-repeat)

[英]Unique identifiers in dynamic form (ng-repeat)

我有一個表單,其中的輸入文本以ng-repeat循環。

對於每個輸入字段,都有一個開關,用戶可通過該開關將“使用默認值”設置為YES / NO。

輸入字段的每一行基本上都是兩個字段,一次要隱藏一個字段,無論是要顯示默認值(開關:是,輸入文本=禁用)還是要設置自定義值(開關:否)

我需要每個元素都有一個唯一的標識符,以便能夠在提交時將其保存,例如** id =“ title _ {{spec.id}}”。

開關起作用,以便使用開關變量創建2way綁定,但這是將保存到數據庫的Switch-DIV中復選框的值。

我想我需要做的是將spec.id值應用於switch-variable =“ useDefaultValue _ {{spec.id}}”“並將相同的值設置為ng-show =” useDefaultValue _ {{spec.id}} “NG-躲 ,但我不知道怎么樣。

HTML:

<div class="row form-group" ng-repeat="spec in specsList">
        <div class="col-xs-6 col-md-6">
            <label for="specification_">{{spec.title}} <span ng-show="spec.unit.length">({{spec.unit}})</span></label>
            <input class="form-control" type="text" name="title_{{spec.id}}" id="title_{{spec.id}}" placeholder="Not visible" ng-model="spec.value" ng-hide="useDefaultValue">
            <input class="form-control" type="text" ng-model="spec.defaultValue" ng-show="useDefaultValue" disabled>
        </div>
        <div class="col-xs-6 col-md-6">
            <label for="useDefaultValue_">Use default value</label> - {{spec.useDefaultValue}}<br />
            <div class="switch" init-switch switch-variable="useDefaultValue">
                <input type="checkbox" id="useDefaultValue_{{spec.id}}" name="useDefaultValue_{{spec.id}}" ng-model="spec.useDefaultValue">
            </div>
        </div>
    </div>

由於您的復選框由與行相關的spec.defaultValue支持,因此您可以提供一個更簡單的解決方案,並且不需要切換。 只需引用spec.useDefaultValue而不是當前的useDefaultValue即可直接訪問它。

<div class="row form-group" ng-repeat="spec in specsList">
        <div class="col-xs-6 col-md-6">
            <label for="specification_">{{spec.title}} <span ng-show="spec.unit.length">({{spec.unit}})</span></label>
            <input class="form-control" type="text" name="title_{{spec.id}}" id="title_{{spec.id}}" placeholder="Not visible" ng-model="spec.value" ng-hide="spec.useDefaultValue">
            <input class="form-control" type="text" name="title_{{spec.id}}" id="title_{{spec.id}}" ng-model="spec.defaultValue" ng-show="spec.useDefaultValue" disabled>
        </div>
        <div class="col-xs-6 col-md-6">
            <label for="useDefaultValue_">Use default value</label> - {{spec.useDefaultValue}}<br />
            <input type="checkbox" ng-model="spec.useDefaultValue">
        </div>
    </div>

順便說一句,我也可以使用ng-if代替ng-showng-hide來減輕頁面亮度並使過渡更加平滑。

編輯提交功能:

$scope.submit = function() {
    angular.forEach(specsList, function(spec, index) {
        if (spec.useDefaultValue) {
            $scope.user[spec.title] = spec.defaultValue;
        }
        else {
            $scope.user[spec.title] = spec.value;
        }
    });
    User.save(user).$promise.then(function(persisted) {
        // do some post-save cleanup
    });
};

當然,這是假設您在用戶上保存了規格值。 它們可以存儲在其他地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM