如何使用ng-model和ng-repeat AngularJS

时间:2018-04-13 09:56:27

标签: html arrays angularjs json frontend

我必须调用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
                    }
                ]
            }
        ]
    };

1 个答案:

答案 0 :(得分:1)

使用输入[复选框]使用NgModel的正确方法可以找到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)">