In AngularJS, you could use ng-hide to hide an HTML element. How would you do this using pure JS/jQuery? If you have something like <div id="userNotLoggedIn"></div>, would it be $("#userNotLoggedIn").hide() or $("#userNotLoggedIn").remove(), or something else? The goal is to not allow a site visitor to view a page if they are not logged in as a user.
2 Answers
Something like
$('#userNotLoggedIn').css('display', 'none');
maybe?
But if you want to be able to apply, and undo it, I recommend putting display: none in it's own class that can be placed and removed at will.
Something like
.myHideClass {
display: none;
}
$(`#userNotLoggedIn`).addClass('myhideClass');
$(`#userNotLoggedIn`).removeClass('myhideClass');
Now when you do whatever logic you have to see if they're logged, when they are logged in do nothing. If they are not logged in, add myHideClass, once they do log in remove myHideClass
Edit:
One problem though, is I'm pretty sure display: none; is still going to have your elements visible in the DOM if you're in something like a debugger.
Angular has a ng-if attr you can drop on tags and tie to a boolean. Like ng-if="userIsLoggedIn" where userIsLoggedIn is a boolean in your controller that's set to true or false.
In the dom while userIsLoggedIn is true the element and everything in it, is in the dom, but; if userIsLoggedIn === false then in the dom if you inspect it, your div is not visible.
What you'll see in the dom is <!--ng-if="userIsLoggedIn"--> And once the boolean flips to true, then the commented html line will turn into all of your actual html.
7 Comments
ng-if is what I'm going after since I don't want anything showing up in the DOM. Would the JS equivalent to ng-if just be a regular if statement?Well if you want to actually replicate ng-hide, then you would use jQuery.addClass method.
ngHide simply watches for the model value bound to it, and consequently adds/removes ng-hide class. This class simply adds a css rule 'display:none' rendering the element hidden.
However, using it for authentication based roles wouldn't usually be a good idea though. You would be simply making it invisible, but it will still be in the DOM and hence accessible.
3 Comments
hide or show. I don't want info accessible from the DOM.ng-hide just does a display: none in CSS, which isn't what I want. ng-if sounds like the answer. By the way, if the page contains sensitive information and you say it shouldn't come from the server, then where should it come from?
ng-hideis probably more equivalent totoggle(condition).hideandremove? Are you not sure what they do?ng-hideadds CSS so the element is not visible.ng-ifdecides whether or not to actually add the element to the DOM. However, like @RahulArora said, you should be restricting navigation to the page.