Knockoutjs-在更新记录Zend时创建依赖下拉列表

时间:2017-01-16 10:21:35

标签: javascript zend-framework knockout.js

我是 knockoutjs 的新手,并创建了一个项目。在这里,我正在更新一个表单,其中有stateId将从中获取城市列表,cityId获取zipcodes等选择状态。         对于初始数组,我在调用Model之前有预取,但是在更新状态时,所有城市都应为空并根据所选的stateID重新填充,依此类推。 我的SelectedCityAction在选择州时没有更新。任何人都可以帮助我吗?

    EditUserAddressModel = function( statesJson, citiesJson , zipcodeJson, Addressdata)  {

        var self = this;
        self.selectedStateAction = ko.observable(Addressdata.state_id);
        self.selectedCityAction = ko.observable(Addressdata.city_id);
        self.selectedZipAction= ko.observable(Addressdata.zipcode_id);
        self.statesArray = ko.observableArray($.parseJSON(statesJson));
        self.citiesArray = ko.observableArray($.parseJSON(citiesJson));
        self.zipcodeArray = ko.observableArray($.parseJSON(zipcodeJson));

        self.selectedStateAction.subscribe(function(newStateValue) {

            self.state_id = newStateValue;
            self.selectedCityAction = undefined;
            self.citiesArray = ko.observableArray();

            $.ajax({
                url: '/profile/getcities?mode=edit&state_id='+self.state_id,
                type: 'get',
                dataType: 'html',
                data: {},
                success: function(data) {
                    self.citiesArray = ko.observableArray($.parseJSON(data));
                }
            })
        });
}

var edit_address_form = document.getElementById("edit-address-form");
        ko.applyBindings( new EditUserAddressModel(resp1[0], resp2[0], resp3[0], Addressdata), edit_address_form);

TPL代码:

<select class="form-control custom-form-control" data_from="edit_city" data-bind="options: $root.statesArray, optionsText: 'state_name', optionsValue: 'state_id', value: selectedStateAction, optionsCaption: 'Select State'"></select>
    <select class="form-control custom-form-control" data_from="edit_zip" id="edit_city" data-bind="options: citiesArray, optionsText: 'city_name', optionsValue: 'city_id', value: selectedCityAction, optionsCaption: 'Select City'"></select>
    <select class="form-control custom-form-control select_zip" id="edit_zip" data-bind="options: $root.zipcodeArray, optionsText: 'zip', optionsValue: 'zipcode_id', value: selectedZipAction, optionsCaption: 'Select Zip'"></select>

1 个答案:

答案 0 :(得分:0)

在这一行:

self.citiesArray = ko.observableArray($.parseJSON(data));

您将旧的observableArray引用替换为与代码和UI的其他部分相关联的新引用。

您需要通过调用新值来设置observableArray

self.citiesArray($.parseJSON(data));