1

I'm attempting to verify if an option other then the default display has been selected. I can not seem to access/verify the empty value for the default case.

I never get to the inner if, I have confirmed I get past the outer. So I'm sure the issue is with my method of accessing 'program_id' I'm just hitting a wall. Any help would be greatly appreciated. Thanks.

programIdsDropDown is JSON populated from a DB.

html

<select
    name="program_id"
    class="form-control"
    ng-model="formData.program_id"
    ng-options="key as value for (key, value) in programIdsDropDown"
>
<option value="">Please select..</option>
</select>
<div ng-show="mainForm.$submitted">
<span class="text-danger" ng-show="shouldChangeProgram()">Please select a Program.<br /></span>
</div>

Controller

$scope.shouldChangeProgram = function() {
var result = false;

if($scope.formData.status == 'closed')
{
    if($scope.formData.program_id == '')
    {
        result = true;
    }
}

$scope.mainForm.status.$setValidity('shouldChangeProgram', !result);

return result;
};
6
  • 1
    Inside your first if, what do you get if you console.log($scope.formData.status)? Also, you can add the required attribute on your <select> and form validation (assuming this is wrapped in a <form> or <ng-form> tag) will set the $valid property to false which you could then simply use. Commented Jan 19, 2017 at 19:53
  • @Lex I get closed as I expect. The dropdown is only required in the state that another dropdown is chosen as closed. It is not required when the the other dropdown is in any other non-closed state. Commented Jan 19, 2017 at 19:59
  • Also, it's just in a bootstrap div <div class="row form-group"> <div class="control-label col-xs-4">Program</div> <div class="col-xs-8"> Commented Jan 19, 2017 at 20:00
  • Oops, I meant console.log($scope.formData.program_id). It must be something other than an empty string if that if statement is not evaluating to true. Commented Jan 19, 2017 at 20:03
  • That type of conditional requirement is exactly what the ng-required directive is for. A value for the control will only be required if the expression in ng-required evaluates to true. You really should consider using a <form> and taking advantage of the validation that Angular provides. It is much more robust than writing a bunch of code in your controllers. Commented Jan 19, 2017 at 20:03

1 Answer 1

4

You should better use :

if(!$scope.formData.program_id) {
   result = true;
}

If problem insists you should check the value of $scope.formData.program_id

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that did exactly what I was wanting.

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.