Home angularjs - Assigned value in controller but select field is still invalid
Reply: 1

angularjs - Assigned value in controller but select field is still invalid

osheh
1#
osheh Published in 2017-12-07 17:14:40Z

I have a select item that the values (multi-select) can be populated in the controller. But when I populate the value in the controller, the select still shows as invalid since this field is required.

Markup as per below.

<div ng-controller="host.views.newAnnouncement.index as vm">
<div class="portlet light bordered" id="form_wizard_1">
    <div class="portlet-title">
        <div class="caption">
            <i class=" icon-speech font-blue"></i>
            <span class="caption-subject font-blue bold">
                New Announcement
            </span>
        </div>
    </div>
    <div class="portlet-body">
        <div class="col-md-12">
            <div class="alert alert-danger" ng-show="vm.isInError">
                <p ng-repeat="message in vm.errorMessages">{{message}}</p>
            </div>
            <ng-form name="vm.announcementForm">

                <div class="form-group form-md-line-input form-md-floating-label no-hint"
                     ng-class="{'has-error': (vm.announcementForm.announcementTypes.$dirty || vm.isValidated) && vm.announcementForm.announcementTypes.$invalid}">
                    <select class="form-control" name="announcementTypes" id="announcementTypes"
                            ng-class="{'edited': vm.model.announcementType}"
                            ng-model="vm.model.announcementType"
                            ng-options="announcementType.id as announcementType.name for announcementType in vm.announcementTypes"
                            required></select>
                    <label for="announcementTypes">Announcement Type</label>
                </div>

                <div class="form-group form-md-line-input no-hint"
                     ng-class="{'has-error': (vm.announcementForm.audienceTypes.$dirty || vm.isValidated) && vm.announcementForm.audienceTypes.$invalid}">
                    <select class="form-control" name="audienceTypes" id="audienceTypes"
                            ng-class="{'edited': vm.model.audienceType}"
                            ng-model="vm.model.audienceType"
                            ng-options="audienceType.id as audienceType.name for audienceType in vm.audienceTypes"
                            ng-change="vm.onAudienceTypeChange()"
                            required></select>
                    <label for="audienceTypes">Audience Type</label>
                </div>

                <div class="form-group form-md-line-input no-hint"
                     ng-class="{'has-error': (vm.announcementForm.audiences.$dirty || vm.isValidated) && vm.announcementForm.audiences.$invalid}">
                    <select class="form-control" name="audiences" id="audiences"
                            ng-class="{'edited': vm.model.audiences}"
                            ng-model="vm.model.audiences"
                            ng-options="audience.id as audience.name for audience in vm.audienceList | orderBy:'name'"
                            multiple required
                            style="min-height:300px;"></select>
                    <label for="audiences">Audience List <span ng-if="vm.model.audiences.length > 0">(Selected: {{vm.model.audiences.length}})</span></label>
                </div>

                <div class="form-group form-md-line-input form-md-floating-label no-hint"
                     ng-class="{'has-error': (vm.announcementForm.subject.$dirty || vm.isValidated) && vm.announcementForm.subject.$invalid}">
                    <input type="text" name="subject" class="form-control" ng-class="{'edited':vm.model.subject}" ng-model="vm.model.subject" maxlength="50" required>
                    <label>Subject</label>
                </div>
                <br />
                <div class="form-group">
                    <label>Details</label>
                    <text-angular ta-text-editor-class="form-content" ta-html-editor-class="form-content" ng-model="vm.model.body"></text-angular>
                </div>

                <div class="row form-group col-md-12">
                    <label class="control-label">Attachement (zip)</label>
                    <input name="file" type="file" id="attachements" nv-file-select="" uploader="vm.fileUploader" accept=".zip"/>
                </div>
            </ng-form>
        </div>
        <hr />
        <div class="row">
            <div class="col-md-12">
                <button type="button" class="btn default button-previous" ng-click="vm.back()">
                    <i class="fa fa-angle-left"></i> Back
                </button>
                <button type="button" class="btn green button-submit"
                        button-busy="vm.saving"
                        busy-text="@L("SavingWithThreeDot")"
                        ng-click="vm.submit()"
                        ng-disabled="vm.announcementForm.$invalid">
                    Submit
                    <i class="fa fa-check"></i>
                </button>
            </div>
        </div>
    </div>
</div>

Controller

    (function () {
    appModule.controller('host.views.newAnnouncement.index', [
        '$scope', '$state', 'FileUploader', 'abp.services.app.hostAnnouncement', 'abp.services.app.hostSettings',
        function ($scope, $state, FileUploader, announcementService, hostSettingsService) {
            var vm = this;

            vm.model = {
                subject: '',
                body: '',
                announcementType: null,
                audienceType: 0,
                audiences: [],
                feedbackId: null
            };

            vm.audienceList = [];

            vm.announcementTypes = [
                { id: 0, name: 'General' },
                { id: 1, name: 'Penalty Invoice' },
                { id: 2, name: 'Other' }
            ];

            vm.audienceTypes = [
                { id: 0, name: 'By Tenant' },
                { id: 1, name: 'By Store Category' },
                { id: 2, name: 'By Floor Location' },
                { id: 3, name: 'By Zone' }
            ];

            vm.fileUploader = new FileUploader({
                url: abp.appPath + 'AnnouncementDocument/UploadFileAsync',
                filters: [
                    {
                        'name': 'enforceMaxFileSize',
                        'fn': function (item) {
                            return item.size <= 2097152; // 2 MiB to bytes
                        }
                    }
                ]
            });

            vm.submit = submit;
            vm.back = back;

            vm.onAudienceTypeChange = onAudienceTypeChange;

            initialize();

            vm.errorMessages = [];

            vm.tenants = [];
            vm.storeCategories = [];
            vm.floorLocations = [];
            vm.zones = [];

            vm.announcementData = {
                announcementId: null,
                setAnnouncementId: function (announcementId) {
                    this.announcementId = announcementId;
                }
            }

            function onAudienceTypeChange() {
                vm.model.audiences = [];
                if (vm.model.audienceType === 0) {
                    vm.audienceList = vm.tenants;
                } else if (vm.model.audienceType === 1) {
                    vm.audienceList = vm.storeCategories;
                } else if (vm.model.audienceType === 2) {
                    vm.audienceList = vm.floorLocations;
                } else if (vm.model.audienceType === 3) {
                    vm.audienceList = vm.zones;
                }
            }

            function initialize() {
                vm.loading = true;
                hostSettingsService.getAllSettings()
                    .success(function (result) {
                        _.each(result.storeCategories.split("|"), function (item) {
                            if (item !== "") {
                                vm.storeCategories.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                        _.each(result.floorLocations.split("|"), function (item) {
                            if (item !== "") {
                                vm.floorLocations.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                        _.each(result.zones.split("|"), function (item) {
                            if (item !== "") {
                                vm.zones.push({
                                    name: item,
                                    id: item
                                });
                            }
                        });

                    }).finally(function () {
                        announcementService.getTenants()
                            .success(function (result) {
                                vm.tenants = result;
                                vm.audienceList = vm.tenants;
                            }).finally(function () {
                                vm.loading = false;
                                autoSelectTenant($state.params);
                            });
                    });
            }

            function autoSelectTenant(stateParams) {
                if (stateParams.tenantId && stateParams.feedbackId) {
                    vm.model.feedbackId = stateParams.feedbackId;
                    vm.model.audienceType = 0;
                    vm.model.audiences.push(stateParams.tenantId);
                }
            }

            function submit() {
                validate();
                if (vm.isInError) return;

                vm.saving = true;
                vm.isValidated = true;

                announcementService.createAnnouncementAsync(vm.model)
                    .success(function (announcementId) {
                        if (vm.fileUploader.queue.length > 0) {
                            vm.announcementData.setAnnouncementId(announcementId);
                            vm.fileUploader.uploadAll();
                        } else {
                            showSuccessNotification();
                        }
                    });
            }

            function back() {
                $state.go('host.announcement');
            }

            function validate() {
                vm.isInError = false;
                vm.errorMessages = [];
                if (vm.model.audiences.length < 1) {
                    vm.errorMessages.push("Please select an audience list.");
                    vm.isInError = true;
                }

                vm.isValidated = true;
            }

            vm.fileUploader.onBeforeUploadItem = function (fileItem) {
                fileItem.formData.push(vm.announcementData);
            };

            vm.fileUploader.onCompleteAll = function () {
                showSuccessNotification();
            };

            function showSuccessNotification() {
                $state.go('host.announcement');
                vm.saving = false;
                abp.notify.success("Announcement has been successfully published.");
            }
        }
    ]);
})();

How do I programmatically set the selection values from the controller and make sure that the field is not invalid? The audiences value is being passes through the $state.params and I've added it to the vm.model.audiences array. But in the UI, vm.model.audiences is still marked as required even though it had values already.

EDIT : I've updated my question with full html and controller. For more clear understanding.

Hadi Jeddizahed
2#
Hadi Jeddizahed Reply to 2017-12-07 17:31:49Z

Try like this

var app = angular.module("app", []);

app.controller('mainCtrl', function($scope) {
  var vm = this;
  vm.model = {
    audiences: []
  };
  vm.audienceList = [{
    "name": "name1",
    "id": 1
  }, {
    "name": "name2",
    "id": 2
  }, {
    "name": "name3",
    "id": 3
  }];

  vm.stateParams = {};
  vm.stateParams.tenantId = 1;
  vm.stateParams.feedbackId = 1;

  vm.autoSelectTenant = function(stateParams) {
    if (stateParams.tenantId && stateParams.feedbackId) {
      vm.model.feedbackId = stateParams.feedbackId;
      vm.model.audienceType = 0;
      vm.model.audiences.push(stateParams.tenantId);
    }
  }


  vm.autoSelectTenant(vm.stateParams);

  vm.stateParams.tenantId = 2;
  vm.stateParams.feedbackId = 2;

  vm.autoSelectTenant(vm.stateParams);

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" />

<div ng-app="app" ng-controller="mainCtrl as vm">
  <select ng-model="vm.model.audiences" ng-options="audience.id as audience.name for audience in vm.audienceList | orderBy:'name'" multiple required></select>
</div>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299023 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO