Mike Thomsen
Mike Thomsen

Reputation: 37526

AngularJS form validation on a bootstrap dropdown

Is it possible to add AngularJS to a Boostrap dropdown (not a <select/>, but rather the Javascript component)? This is what I have:

<div class="form-group has-feedback" ng-class="{'has-error': editorForm.example.$invalid && !editorForm.example.$pristine, 'has-success': editorForm.example.$valid && !editorForm.example.$pristine}">
        <label for="example">Example</label>

        <div class="dropdown" id="example" style="width: 90%">
            <button class="btn btn-default dropdown-toggle" type="button" id="dropdown"
                    data-toggle="dropdown">
                {{exampleLabel}}
                <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                <li data-ng-repeat="example in examples" role="presentation"><a
                        role="menuitem" tabindex="-1"
                        data-ng-click="selectExample(example)"
                        href="javascript:void(0);">{{example.label}}</a>
                </li>
            </ul>
        </div>

$scope.selectExample = function(val) {
    $scope.example = val;
}

Is there a way for me to programatically set the validity in selectExample?

Upvotes: 3

Views: 2636

Answers (3)

Panteleimon.Kylish
Panteleimon.Kylish

Reputation: 185

Add input type="hidden":

<form class="form-validation" name="actin_form">
    <div uib-dropdown>
        <input type="hidden" name="nameVal" ng-model="nameValModel" required/>
        <button type="button" ng-class="{'input-error': actin_form.nameVal.$invalid}" class="btn" uib-dropdown-toggle>
            <span>{{nameValModel}}</span>
        </button>
        <ul class="dropdown-menu">
            <li ng-repeat="type in list" class="text-wrap">
                <span>{{type.name}}</span>
            </li>
        </ul>
    </div>
</form>

Upvotes: 2

Nalin
Nalin

Reputation: 111

This work for me.hope you can get some idea.

<style>

.dropdown-has-error{
    border-color: #a94442;//bootsrtap warning color
}

</style>

add ng-class directive to the dropdown button

ng-class="{'dropdown-has-error' : example == ''}

in the controller

$scope.example = '';

$scope.selectExample = function(val) {
    $scope.example = val;
}

or you can check condition as in the above post,

ng-class="{'dropdown-has-error' : myForm.exampleLabel.$error.required}

Upvotes: 0

Rana
Rana

Reputation: 1218

Add this hidden text box:

<input type="text" name="exampleLabel" ng-model="exampleLabel" hidden required />

and add this validation after the dropdown

 <span class="text-danger" ng-show="myForm.exampleLabel.$error.required">
                    validation message
                </span>

Upvotes: 2

Related Questions