简体   繁体   中英

Show/hide elements using ng-show/ng-hide based on certain conditions

I have the following:

<input class="form-field form-control" type="text" 
     name="Website" ng-model="vm.infodata.Website"
     placeholder="Website Address" maxlength="50"
     required ng-pattern="/^(www\.)?[a-zA-Z0-9_\-]+\.([a-zA-Z]{2,4}|[a-zA-Z]{2}\.[a-zA-Z]{2})(\/[a-zA-Z0-9\-\._\?\&=,'\+%\$#~]*)*$/"
     ng-readonly="vm.isreadonly" ng-disabled="vm.applyDisabled">
     <div class="form-field form-control disabled" >
         <a target="_blank" href='http:\\{{vm.infodata.Website}}'>{{vm.infodata.Website}} </a>
     </div>

Essentially, the requirement is, if the user enters a URL in the input and saves the next time the page loads it will display as a link rather than an input field. - If there is no data in vm.infodata.Website when the page loads then show the input and hide the link. - If there is data in vm.infodata.Website when the page loads hide the textbox and show the link - If the edit button is clicked hide the link and show the textbox

This field is required. However, there are email address fields that will need to behave the same way but are not required fields. Is there a way to do this in angular without setting a bunch Boolean values to true and false and hiding/showing the different fields based on that?

I ended up changing the code a bit.

I now have the input field with a placeholder for when the "edit" button is clicked

 <input class="form-field form-control" ng-show="vm.visibleBoolean" required placeholder="Credit Union Website" 
                                       ng-pattern="/^(www\.)?[a-zA-Z0-9_\-]+\.([a-zA-Z]{2,4}|[a-zA-Z]{2}\.[a-zA-Z]{2})(\/[a-zA-Z0-9\-\._\?\&=,'\+%\$#~]*)*$/" 
                                       name="CUWebsite" type="text" ng-model="vm.cuinfodata.Website" maxlength="50" 
                                       ng-readonly="vm.isreadonly" ng-disabled="vm.applyDisabled">

Then under that I'm using ng-bind-html:

<div class="form-field form-control disabled" ng-hide="vm.visibleBoolean" ng-bind-html="cuWebsite"></div>

In the controller if there is no data I'm doing this:

$scope.cuWebsite = "<span class='placeholder'>Your Website</span>"

And when there is data I'm doing this:

$scope.cuWebsite = "<a href='http://" + vm.cuinfodata.Website + "' target='_blank'>" + vm.cuinfodata.Website + "</a>";

The ng-hide properties are being set when the edit button is clicked. It might not be an elegant way to do this but it fulfills the requirement.

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