简体   繁体   中英

only show button if input fields are not empty and one has valid URL

I have the following code and it works fine to check if the input field "inputURL" has a valid URL, if it has the anchor link a.btn shows fine but I also only want it to show if both have been filled in. How can I add to the ng-show in the anchor to do this?

<form name="myForm" class="row inputs">
          <div class="col-xs-5">
              <label for="exampleInputPassword1">Enter a Title/Description</label>
                <input type="text" id="urlName" class="form-control" placeholder=""  ng-model="mvName" >
            </div>
            <div class="col-xs-5">
                <label for="exampleInputPassword1">Enter a URL</label>
                <input type="url" name="inputURL" id="urlLink" class="form-control" placeholder=""  ng-model="mvUrl" >
          </div>
          <div class="col-xs-2">
              <a href="javascript:" ng-click="saveToList($event)" class="btn btn-block post" ng-show="myForm.inputURL.$valid  ">Post</a>
          </div>
        </form>

You can check if both have been filled with the model like this:

ng-show="myForm.inputURL.$valid && mvName && nvUrl"

or with the view value of the input

ng-show="myForm.inputURL.$valid && myForm.inputURL.$viewValue && myForm.urlName.$viewValue"

You can use the required HTML5 special attribute to check if the input is not empy.

 <form name="myForm" class="row inputs">
      <div class="col-xs-5">
          <label for="exampleInputPassword1">Enter a Title/Description</label>
            <input type="text" name="mvName id="urlName" class="form-control" placeholder=""  ng-model="mvName" required>
        </div>
        <div class="col-xs-5">
            <label for="exampleInputPassword1">Enter a URL</label>
            <input type="url" name="inputURL" id="urlLink" class="form-control" placeholder=""  ng-model="mvUrl" required>
      </div>
      <div class="col-xs-2">
          <a href="javascript:" ng-click="saveToList($event)" class="btn btn-block post" ng-show="myForm.inputURL.$valid && !myForm.inputURL.$error.required && !myForm.mvName.$error.required">Post</a>
      </div>
    </form>

However, to clean the view a little bit, I would suggest using a controller. Expose a function which returns true or false if the form is valid. And simply use ng-show="isValid() ".

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