在下一行中单击select2时如何防止select2清除所选值

问题描述 投票:1回答:1

我的Web应用程序使用angularjs和php。在网站上,有一个部分可以添加用户的估算值。它具有select2作为下拉列表,可填充库存中的现有项目。

<tr class="valign-top"
   ng-repeat="estimate in workorder.steps[1].estimates track by $index"
   ng-init="item_key = $index">
     <div id="material_div{{$index}}"
            ng-if="estimate.type == 'material'"
            class="create_Wo_forms  inspec_crt_forms margin-0">
            <select
                style="width: 100%!important;"
                id="parts_selected{{$index}}"
                stepIndex="{{estimatesselectedStep}}"
                itemIndex="{{$index}}"
                class="crt-wo-input inspec-input"
                item_wo_create_select>
            </select>
     </div>
</tr>

整个部分在HTML文件中的ng-repeat中。

directive('itemWoCreateSelect', function () {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            var stepIndex = attrs.stepindex;
            var elemIndex = attrs.itemindex;
            var item = scope.workorder.steps[stepIndex]['estimates'][elemIndex];
            $(elem).append('<option>' + item['name'] + '</option>');
            scope.selected_items = [];
            angular.forEach(scope.workorder.steps[stepIndex]['estimates'], function (v) {
                if (v['item_id'] && v['item_id'] != null && !(v['item_id'] == item['item_id'] && v['unit_cost'] == item['unit_cost'])) {
                    scope.selected_items.push({ 'item_id': v['item_id'], 'unit_price': v['unit_cost'] });
                }
            });
            var formatRepo = function (repo) {
                if (repo.loading)
                    return repo.text;
                var markup = '<span class="label">';
                if (repo.hasOwnProperty('item_name') && repo.item_name.trim()) {
                    markup += repo.item_name + ' (' + repo.unit_price + ')' + '';
                } else {
                    markup += repo.text + '';
                }
                markup += '</span>';
                return markup;
            };

            var formatRepoSelection = function (repo) {
                if (repo.hasOwnProperty('item_name')) {
                    return repo.item_name + ' (' + repo.unit_price + ')';
                } else {
                    item['name'] = repo.id;
                    return repo.id;
                }
            };
            $(elem).select2({
                placeholder: "Search for item",
                tags: true,
                ajax: {
                    type: 'POST',
                    url: version5Url + 'inventory/getMasterStocksForInvoice',
                    tags: true,
                    data: function (params) {
                        return {
                            token: scope.token,
                            user_id: scope.user_id,
                            client_id: scope.client_id,
                            search: params.term,
                            selected_items: scope.selected_items
                        };
                    },
                    dataType: 'json',
                    delay: 250,
                    processResults: function (data, params) {

                        $(elem).find('option').remove();
                        if (item['item_id']) {
                            delete item['item_id'];
                        }
                        item['unit_cost'] = 0;
                        item['applied_taxes'] = [];
                        item['selected_tax'] = [];
                        item['amount'] = 0;
                        item['quantity'] = 0;
                        item['description'] = '';
                        scope.details = data.parts;
                        scope.$apply();
                        return {
                            results: data.parts,
                            pagination: false
                        };
                    },
                    cache: false
                },
                escapeMarkup: function (markup) {
                    return markup;
                },
                minimumInputLength: 0,
                templateResult: formatRepo,
                templateSelection: formatRepoSelection
            });

            $(elem).on("select2:select", function () {
                var index = parseInt($(elem).val());
                console.log("Slect", index)
                if (!isNaN(index)) {
                    angular.forEach(scope.details, function (value, k) {
                        if (value['id'] == index) {
                            item['quantity'] = 1;
                            item['lot_number'] = value.lot_number;
                            item['item_id'] = value.item_id;
                            item['name'] = value.item_name + ' (' + value.unit_price + ')';
                            item['description'] = value.item_description;
                            item['unit_cost'] = value['unit_price'];
                            item['applied_taxes'] = [];
                            item['selected_tax'] = [];
                            if (value['taxes'] != '' && value['taxes'] != null) {
                                var tax_array = value['taxes'].split(',').map(function (x) {
                                    return parseInt(x);
                                });
                                angular.forEach(scope.newTaxes, function (value, key) {
                                    angular.forEach(tax_array, function (v1, k1) {
                                        if (value['tax_id'] == v1) {
                                            tax_array.splice(k1, 1);
                                        }
                                    });
                                });
                                item['applied_taxes'] = tax_array;
                                angular.forEach(tax_array, function (value) {
                                    var result = scope.taxes.filter(function (obj) {
                                        return obj.tax_id == value;
                                    });
                                    if (result.length > 0) {
                                        item['selected_tax'].push(result[0].tax_name + ' (' + result[0].rate + '%)');
                                    }
                                });
                            }
                        }
                    });
                } else {
                    if (item['item_id']) {
                        delete item['item_id'];
                    }
                    item['unit_cost'] = 0;
                    item['applied_taxes'] = [];
                    item['selected_tax'] = [];
                    item['amount'] = 0;
                    item['quantity'] = 0;
                    item['description'] = '';

                }
                scope.$apply();
            });
        }
    };
})

select2由js文件中的指令初始化。

所有这些功能都可以在select2版本3.x中使用。但是我最近将select2升级到版本4.0.13,估计部分中的select2下拉列表无法正常工作。

问题:第一行中的选择很好。添加新行后,第一行的select2下拉列表中的选定值将被清除。Only the first-row selection works finewhen the select2 in 2nd row is opened the selected value in the first select2 gets cleared.

如果需要,请询问更多信息。预先感谢!

angularjs angularjs-directive angularjs-ng-repeat jquery-select2 jquery-select2-4
1个回答
0
投票

Joe Enzminger's Anwser开始,这里的技巧是将select2初始化包装在超时函数中,以便将这些选项作为常规选择下拉列表的一部分在DOM中提供。只有在选项成为DOM的一部分之后,下拉列表才能转换为select2下拉列表。

第一个$ timeout是必需的,因为这些选项将不在DOM,直到下一个摘要周期。问题是新的如果以后更改了模型,则不会将选项添加到控件中您的应用程序。

    $timeout(function() {
        $(elem).select2({
            placeholder: "Search for item",
            tags: true,
            ajax: {
                type: 'POST',
                url: version5Url + 'inventory/getMasterStocksForInvoice',
                tags: true,
                data: function (params) {
                    return {
                        token: scope.token,
                        user_id: scope.user_id,
                        client_id: scope.client_id,
                        search: params.term,
                        selected_items: scope.selected_items
                    };
                },
                dataType: 'json',
                delay: 250,
                processResults: function (data, params) {

                    $(elem).find('option').remove();
                    if (item['item_id']) {
                        delete item['item_id'];
                    }
                    item['unit_cost'] = 0;
                    item['applied_taxes'] = [];
                    item['selected_tax'] = [];
                    item['amount'] = 0;
                    item['quantity'] = 0;
                    item['description'] = '';
                    scope.details = data.parts;
                    scope.$apply();
                    return {
                        results: data.parts,
                        pagination: false
                    };
                },
                cache: false
            },
            escapeMarkup: function (markup) {
                return markup;
            },
            minimumInputLength: 0,
            templateResult: formatRepo,
            templateSelection: formatRepoSelection
        });
});
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.