【问题标题】:How to push list of objects to model using ng-model and ng-repeat AngularJS如何使用 ng-model 和 ng-repeat AngularJS 将对象列表推送到模型
【发布时间】:2018-09-23 15:34:29
【问题描述】:

我要调用一个POST函数,并且需要提前将web表单中的数据压缩成一个对象。我使用 ng-repeat 显示所有数据输入,并为输入初始化这个值,但我不知道如何使用 ng-model 来保存数据。 我可以通过为输入设置动态 id 并使用 JQuery 获取数据来解决这种情况,但这不是一个好的解决方案。我只想使用 AngularJS 模型。 请给我一个建议。下面是我的代码: Click here to see the screenshot of UI form

html 文件

<!-- edit-user-page-view -->

<div spectrum-error-container
     data-scope-id="$id"
     class="col-sm-12"></div>

<div class="email-preference-block">
    <form name="editUserForm"
          id="editUserForm"
          role="form"
          class="prj-form prj-create-user-form">

        <fieldset id="fieldsetAccountInformation">
            <legend>{{ 'user.userPage.form.fieldsets.accountInformation' | translate }}</legend>
            <div class="row language-preference-block">
                <div class="form-group">
                    <div class="col-md-12 col-sm-12">
                        <label data-translate="user.userPage.form.preferredLanguage"></label>
                    </div>
                    <div class="col-md-12 col-sm-12">
                        <label data-ng-repeat="option in preferencesData.languageOptionList"
                               class="radio-inline">
                            <input type="radio"
                                   ng-model="emailNotificationModel.selectedLanguageValue"
                                   value="{{ option.value }}"> {{ option.label | translate }}
                        </label>
                    </div>
                </div>
            </div>

            <div class="row user-preference-block">
                <table data-ng-repeat="preferenceItem in preferencesData.userNotificationPreferencesList"
                       class="table table-bordered table-striped user-preference-table">
                    <thead>
                    <tr>
                        <th>{{ preferenceItem.label | translate }}</th>
                        <th>{{ 'organisation.mediaPreference.selected' | translate }}?</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr data-ng-repeat="mediaOption in preferenceItem.mediaOptionList">
                        <td class="first-column">
                            {{ mediaOption.label | translate}}
                        </td>
                        <td class="second-column">
                            <input type="checkbox"
                                   id="inputStatus1-{{ mediaOption.id }}"
                                   value="{{ mediaOption.id }}"
                                   ng-checked="mediaOption.userChoice"
                                   data-ng-click="clickHandler.checkValue(mediaOption.id)">
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>

            <div class="prj-form-actions"
                 data-spectrum-style-affix
                 data-threshold="150"
                 data-css-class="sdx-sticky-container">
                <button id="selectAllButton"
                        class="btn btn-default"
                        type="button"
                        data-ng-click="clickHandler.selectAll()"
                        data-translate="global.buttons.selectAll">
                </button>
                <button id="deselectAll"
                        class="btn btn-default"
                        type="button"
                        data-ng-click="clickHandler.deselectAll()"
                        data-translate="global.buttons.deselectAll">
                </button>
                <button id="saveBtn"
                        class="btn btn-default"
                        type="button"
                        data-ng-click="clickHandler.saveButton()"
                        data-translate="global.buttons.save">
                </button>
                <button id="cancelBtn"
                        class="btn btn-default"
                        type="button"
                        data-ng-click="clickHandler.deselectAll()"
                        data-translate="global.buttons.cancel">
                </button>
            </div>
        </fieldset>
    </form>
</div>

<div class="clearfix"></div>

<!-- / edit-my-account-page-view -->

控制器文件:

    angular.module(
    'EditUserPreferencesPageControllerModule',
    []
).controller(
    'EditUserPreferencesPageController',
    [
        '$scope',
        '$location',
        '$routeParams',
        '$filter',
        '$window',
        '$modal',
        'PageTitleModel',
        'SpectrumPageHeaderModel',
        'AccountModel',
        'UserModel',
        'OrganisationService',
        'RolesModel',
        'MediaPreferencesModel',
        'UserService',
        'EmailNotificationService',
        'EmailNotificationModel',
        'SpectrumErrorModel',
        'SpectrumHATEOASHelper',
        function ($scope,
                  $location,
                  $routeParams,
                  $filter,
                  $window,
                  $modal,
                  PageTitleModel,
                  SpectrumPageHeaderModel,
                  AccountModel,
                  UserModel,
                  OrganisationService,
                  RolesModel,
                  MediaPreferencesModel,
                  UserService,
                  EmailNotificationService,
                  EmailNotificationModel,
                  SpectrumErrorModel) {
            var impersonateUserCode = AccountModel.account.impersonatedUserCode,
                userCode = impersonateUserCode ? impersonateUserCode : $routeParams.userCode;
            $scope.mediaPreferencesModel = MediaPreferencesModel;
            $scope.userModel = UserModel;
            $scope.emailNotificationModel = EmailNotificationModel;
            $scope.rolesModel = RolesModel;
            $scope.statusList = [];
            $scope.relationshipNotificationList = [];
            $scope.auditNotificationList = [];
            $scope.testListMediaValue = [];

            $scope.preferencesData = {};

            $scope.pleaseSelect = $filter('translate')('global.placeholders.pleaseSelect');

            function initialise() {
                PageTitleModel.setTitle('user.pageTitles.emailNotification');
                SpectrumPageHeaderModel.setTitle('user.pageTitles.emailNotification');
                SpectrumErrorModel.clearErrorsForScope($scope.$id);
                generateOptions();
                loadUserData();
            }

            function generateOptions() {
                for (var status in MediaPreferencesModel.STATUS) {
                    if (MediaPreferencesModel.STATUS[status].domainType === 'Relationship') {
                        $scope.relationshipNotificationList.push(MediaPreferencesModel.STATUS[status]);
                    } else if (MediaPreferencesModel.STATUS[status].domainType === 'Audit') {
                        $scope.auditNotificationList.push(MediaPreferencesModel.STATUS[status]);
                    }
                }
            }

            function loadUserData() {
                UserService.getOne(userCode).then(
                    function successHandler(successResponse) {
                        UserModel.populateFromJSON(successResponse.data);
                        getNotificationPreferences();
                    },
                    function errorHandler(errorResponse) {
                        SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
                    }
                );
            }

            function getNotificationPreferences() {
                EmailNotificationService.getNotificationPreferences(UserModel.userCode).then(
                    function successHandler(successResponse) {
                        $scope.preferencesData = successResponse.data;
                        EmailNotificationModel.populateData($scope.preferencesData);
                    },
                    function errorHandler(errorResponse) {
                        SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
                    }
                );
            }

            function saveData() {
                var a = $scope.testListMediaValue;
                EmailNotificationService.saveNotificationPreferences(UserModel.userCode, EmailNotificationModel.getJsonForSavePreferences()).then(
                    function successHandler(successResponse) {
                        console.log(successResponse);
                    },
                    function errorHandler(errorResponse) {
                        SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
                    }
                );
            }

            $scope.clickHandler = {
                saveButton: function () {
                    saveData();
                },
                backButton: function () {
                    $location.path(viewUserPath());
                },
                selectAll: function () {
                    angular.forEach(MediaPreferencesModel.relationshipStatus, function (itm) {
                        itm.userChoice = true;
                    });
                },
                deselectAll: function () {
                    angular.forEach(MediaPreferencesModel.relationshipStatus, function (itm) {
                        itm.userChoice = false;
                    });
                },
                checkValue: function (isChecked) {
                    console.log(isChecked);
                }
            };

            function viewUserPath() {
                return '/user/view/' + userCode;
            }

            $scope.canShow = {
                emailPreferences: function () {
                    var preferenceFields = MediaPreferencesModel.preferenceFields;
                    return (preferenceFields.length > 0);
                },
                isRelationshipNotification: function (reference) {
                    return reference.domainType === 'Relationship';
                },
                isAuditNotification: function (reference) {
                    return reference.domainType === 'Audit';
                }
            };

            initialise();
        }
    ]
);

型号

angular.module(
    'EmailNotificationModelModule',
    []
).factory(
    'EmailNotificationModel', [
        function () {
            return {
                selectedLanguageValue: '',
                userNotificationPreferencesList: [],
                getJsonForSavePreferences: function () {
                    var json = {};

                    json.selectedLanguageValue = this.selectedLanguageValue;
                    json.userNotificationPreferencesList = this.userNotificationPreferencesList;

                    return json;
                },
                populateData: function (preferencesData) {
                    this.selectedLanguageValue = preferencesData.selectedLanguage.value;
                }
            };
        }
    ]
);

我调用get函数生成表单时解析JSON

{
        selectedLanguage: {
            label: 'Spain',
            value: 'sp'
        },
        languageOptionList: [
            {
                label: 'English',
                value: 'en'
            },
            {
                label: 'Chinese',
                value: 'cn'
            },
            {
                label: 'Spain',
                value: 'sp'
            },
            {
                label: 'French',
                value: 'fr'
            },
            {
                label: 'Portuguese',
                value: 'po'
            },
            {
                label: 'Japanese',
                value: 'jp'
            }
        ],
        userNotificationPreferencesList: [
            {
                label: 'organisation.mediaPreference.tradingRelationships',
                domainType: 'tradingRelationShip',
                mediaOptionList: [
                    {
                        id: 'ACCEPTED',
                        label: 'organisation.relationshipStatuses.accepted',
                        order: 1,
                        userChoice: true
                    },
                    {
                        id: 'INITIATED',
                        label: 'organisation.relationshipStatuses.initiated',
                        order: 2,
                        userChoice: false
                    },
                    {
                        id: 'REJECTED',
                        label: 'organisation.relationshipStatuses.rejected',
                        order: 3,
                        userChoice: true
                    }
                ]
            },
            {
                label: 'organisation.mediaPreference.auditNotifications',
                domainType: 'auditNotification',
                mediaOptionList: [
                    {
                        id: 'AUDIT_CREATED',
                        label: 'organisation.auditStatuses.created',
                        order: 4,
                        userChoice: true
                    },
                    {
                        id: 'AUDIT_ACCEPTED',
                        label: 'organisation.auditStatuses.accepted',
                        order: 5,
                        userChoice: false
                    }
                ]
            }
        ]
    };

【问题讨论】:

    标签: html arrays angularjs json frontend


    【解决方案1】:

    NgModel 与 input[checkbox] 的正确使用方法可以在here找到。

    为了你的实现,改变这个

    <input type="checkbox"
           id="inputStatus1-{{ mediaOption.id }}"
           value="{{ mediaOption.id }}"
           ng-checked="mediaOption.userChoice"
           data-ng-click="clickHandler.checkValue(mediaOption.id)">
    

    到这里

    <input type="checkbox"
           ng-model="mediaOption.userChoice"
           ng-change="clickHandler.checkValue(mediaOption.id)"> 
    

    【讨论】:

    • 是的。如果我在表单中修复了复选框就可以了,然后我可以像你的建议一样将 ng-model 设置为输入。但问题是复选框输入是从后端动态生成的。所以我更新了你推荐的代码,它可以获取数据,但它没有向模型出价。
    • @SonPham 你的意思是当 ypu 选中/取消选中 checkox 时 userChoise 值没有改变?
    猜你喜欢
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 2014-10-19
    • 2014-09-30
    • 2019-10-25
    相关资源
    最近更新 更多