AngularJS在引导下拉列表中进行表单验证

时间:2014-09-19 18:55:40

标签: javascript angularjs twitter-bootstrap

是否可以将AngularJS添加到Boostrap下拉列表中(不是<select/>,而是Javascript组件)?这就是我所拥有的:

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

我有办法以编程方式设置selectExample的有效性吗?

3 个答案:

答案 0 :(得分:1)

添加此隐藏文本框:

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

并在下拉列表中添加此验证

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

答案 1 :(得分:1)

添加输入类型=&#34;隐藏&#34;:

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

答案 2 :(得分:0)

这项工作对我来说。你可以得到一些想法。

<style>

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

</style>

ng-class指令添加到下拉按钮

ng-class="{'dropdown-has-error' : example == ''}
控制器中的

$scope.example = '';

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

或者您可以按照上面的帖子检查条件,

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