简体   繁体   中英

How to make dropdown selection compulsory if the variable is true?

I have an angular js dropdown. I want that if my variabl eg 'x' has value true it makes it compulsory to select a value from the drop down and incase of false value it can allow it to save it without selecting anything from the drop down. Here is my drop down:

<select class="form-control dropdownheight"
        ng-model="search.hardware"
        ng-change="search()" >
    <option value="" selected>Select Hardware</option>
    <option ng-repeat="box in boxes" value="{{box.name}}">{{box.name}}</option>
</select>

Use the ng-required directive :

<select class="form-control dropdownheight"
        ng-model="search.hardware"
        ng-change="search()"
        ng-required="x">
    <option value="" selected>Select Hardware</option>
    <option ng-repeat="box in boxes" value="{{box.name}}">{{box.name}}</option>
</select>

See this jsfiddle

You can use ng required for this.

     <form name="form">
    <select  ng-model="hardware"  class="form-control dropdownheight" ng-change="search()" >
<option value="" selected>Select Hardware</option>
<option ng-repeat="box in boxes" value="{{box.name}}">{{box.name}}</option>
                                </select>

    <label for="input">This input must be filled if `required` is true: </label>
    <input type="text" id="input" name="input" ng-required="isRequired" /><br>
    <hr>
    <code>{{form.input.$error}}</code><br>
    isRequired = <code>{{isRequired}}</code>

    <input type="submit" value="Save" ng-disabled="isRequired"/>
  </form>

I have created plunkr for it:

https://plnkr.co/edit/bfWuGCOYLGIV0Krlaaeo?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM