0

I have to call a POST function, and need to compress the data in web form into an object in advance. I use ng-repeat to display all data input, and init this value for input, but I have no idea how to use ng-model to save the data. I can resolve this case by setting an dynamic id for input, and using JQuery to get data, but it's not a good solution. And I want use AngularJS model only. Please give me an advice. Below is my code: Click here to see the screenshot of UI form

html file

<!-- 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 -->

controller file:

    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();
        }
    ]
);

model

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;
                }
            };
        }
    ]
);

JSON parse when I call get function to generate form

{
        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 Answer 1

1

The correct way to use NgModel with input[checkbox] can be found here.

For your implementation, change this

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

To this

<input type="checkbox"
       ng-model="mediaOption.userChoice"
       ng-change="clickHandler.checkValue(mediaOption.id)"> 
Sign up to request clarification or add additional context in comments.

2 Comments

Yes. It's ok if I have fixed checkbox in form, then I can set ng-model to the input like your suggestion. But the problem is the checkbox input is dynamically generate from back-end. So I has updated code like your recommendation, it get data ok, but it's not biding data to the model.
@SonPham do you mean that when ypu check/uncheck the checkox the userChoise value isn't changed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.