Angular ng-if multiple conditions not working - javascript

This is a relatively simple question but I cannot figure out why this isn't working.
So I have ng-if statement in HTML where I check condition if its not true. as in:
<div class="new-asset" data-ng-if="$root.questionData.question_type_id != '1' || $root.questionData.question_type_id != '8'">
But for some reason this does not work. I also tried:
<div class="new-asset" data-ng-if="($root.questionData.question_type_id != '1' || $root.questionData.question_type_id != '8')">
Which has no affect whatsoever... I was reading up and trying to find a solution, someone suggested placing the condition in controller, which would also have performance increase (not 100% sure if it would), as in:
$scope.addNewAssetIf = $root.questionData.question_type_id != '1' || $root.questionData.question_type_id != '8';
and then referencing it in html as:
<div class="new-asset" data-ng-if="addNewAssetIf">
But I cannot use this approach due to asynchronous loading, and dependencies. I need to make this work somehow, I get no errors or anything, even though the question_type_id is 1 I still get .net-asset div shown. If I remove OR statement and only have 1 condition it works:
<div class="new-asset" data-ng-if="$root.questionData.question_type_id != '1' || $root.questionData.question_type_id != '8'">
Any help is appreciated.
Thanks

I'm ignoring everything angular related and trying to understand the basic logic behind the condition. If the ID == 1 won't it satisfy the second condition which asks it to be different from 8? And isn't that true for cases where the ID is 8?
In other words, don't you need && instead of ||?
This should really be a comment but I don't have enough reputation.

Try using a function:
$scope.addNewAssetIf = function() {
return $root.questionData.question_type_id != '1' || $root.questionData.question_type_id != '8';
};

Could you try using $rootScope instead of $root and include $rootScope as a dependency in your controller? The issue could just be that the variable is not in scope. You could also assign this to your $scope and then reference it directly in your template
Basically, the idea is to try and see if the values are bound to your template fine. You could even try and
{{$root.questionData.question_type_id}}</div>
To verify this, and then if not, start by addressing the root cause.

Related

else operator | JS | Chrome extention

I have this function:
function FizzBuzz(){
if(document.getElementById("textbox") == true){
Fizz();
} else {
Buzz();
}
}
The Fizz() and Buzz() functions place text in textboxes specified by document.getElementById in their own functions.
in it's current configuration, it should to my understanding execute Fizz() if ("textbox") is found on the webpage, otherwise Buzz() should be executed. This does not happen, and it will only execute one of them, no matter if ("textbox") is true or not.
The ("textbox") referenced above only exists on one of the two pages this is designed to work with.
Changing to !== true will invert the effect, the same with == false, as with the current behavior is expected. I have also tried to check for == null and !== null, this results in the same behavior.
I simply do not understand what I'm doing wrong here.
document.getElementById returns either null or element. So, comapring both with == or === with true or false will always return false.
You can directly put document.createElement inside if as a condition.
If you still face the issue, I suggest you to put a break point and see how the code is executed.
Sample code for better understanding - https://codepen.io/Yash__/pen/WNzgYvL?editors=1111
<h1 id="hai">hai</h1>
if(document.getElementById('hai')){
console.log("there");
}else{
console.log("not there")
}

How to make true && false equal to true in angularjs expression?

I'm trying to check if an input has been touched and is empty (without the built in functions in angular).
<form-input is-invalid-on="isTouched && !gs.data.name || gs.data.name.length > 50"></form-input>
If isTouched && !gs.data.name evaluates to true && false then that side of the expression becomes false
So my question is quite simple, how do I make the entire expression evaluate to true if the input has been touched and if it's empty or has a length greather than 50?
I believe it is used as attribute directive.
is-invalid-on="(isTouched && gs.data.name.length) || gs.data.name.length > 50"
Reason? I assumed your gs.data.name is a string. Empty string when evaluated in javascript is still a truthy value. So you must evaluate it to length.
<form-input is-invalid-on="(isTouched && !gs.data.name) || (gs.data.name.length > 50)"</form-input>
can try using () and also check gs.data like isTouched && (!gs.data || !gs.data.name || !gs.data.name.length || gs.data.name.length > 50)
<form-input is-invalid-on="isTouched && (!gs.data || !gs.data.name || !gs.data.name.length || gs.data.name.length > 50)"></form-input>
Angular expression does not work exactly the same than javascript from what i got try this one :
<form-input is-invalid-on="isTouched && gs.data.name.length==0 || gs.data.name.length > 50"></form-input>
Assuming you properly initialized gs.data.name to empty string.
By the way you forgot the > on your tag.
I finally found the reason as to why it was behaving so strange, and as this question has many answers I could not delete it. So I might as well explain what happened.
It turned out that isTouched was always undefined because I was using it outside of the directive (even if it was used in an attribute of the directive) which made the expression undefined && false, resulting in isInvalidOn always being false.
Instead I made it so that I used isTouched later in the actual form-input template as ng-class={invalid: isInvalidOn && isTouched}, resulting in the desired behavior.

Angular ngClass is not updating my classes even though my condition change as expected

I have something like this in a template I am creating
<div ui-view id="app" class="nng-3" ng-class="{ 'app-mobile': app.isMobile, 'app-navbar-fixed': app.layout.isNavbarFixed, 'app-sidebar-fixed': app.layout.isSidebarFixed, 'app-sidebar-closed': app.layout.isSidebarClosed, 'app-footer-fixed': app.layout.isFooterFixed }"></div>
The values app.layout.isNavbarFixed, etc are initialized with either zero or one, and for the first time the page loads the appropriate classes are inserted into my div. Any change after that though, by means of a button that sets those values, is not reflected on my class attributes by ng-class.
If I directly print those variables in my template, eg. {{app.layout.isSidebarFixed}} I can see them changing from true to false and vice versa, but ng-class will not update or remove any new classes.
I am not sure where to begin and look for the solution for this since with my limited knowledge I cant spot any obvious mistake immediately. Does anyone have any idea on what causes this issue?
A workaround of mine is to manipulate a model variable just for the ng-class toggling:
1) Whenever my list is empty, I update my model:
$scope.extract = function(removeItemId) {
$scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
if (!$scope.list.length) {
$scope.liststate = "empty";
}
}
2) Whenever my list is not empty, I set another state
$scope.extract = function(item) {
$scope.list.push(item);
$scope.liststate = "notempty";
}
3) I use this additional model on my ng-class:
ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty'}"
Update*: Also you can add any other states if needed and use at ng-class like:
ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-additional-state', liststate == 'additional-state'}"
Because you know, an initially empty list state is not equal with a list which is emptied by command.
Probably the ng-class implementation is not considering "0" to be "false" as you expect, because it's doing an strict comparision with ===.
Try expressing the conditions like this:
ng-class="{ 'app-mobile': app.isMobile == 0, 'app-navbar-fixed': app.layout.isNavbarFixed == 0, ...
Tried your variant. Have everything working. Please, check if your button click event is on $scope and AngularJS knows, that values changed.
For example, if function triggered by native DOM Event (some jQuery table updated or something) than you should use $apply function, to reflect changes on scope. Something like this:
$scope.eventHandler = function(e) {
$scope.$apply(function(){ $scope.someProp = e.value;}
}
In the mean time, check this jsfiddle
Update:
Please check this jsfiddle out. This works in AngularJS 1.4.8, but doesn't in other, that support jsfiddle. From what I know, it's not really a best idea to do an assignment inside of expression, the controller is meant for this thing.

JQuery - write conditional when object property is blank

I'm trying to write a conditional for when an object property's value is blank, but it is not triggering. This is my code. Any idea how I should write this?
console.log(vid);
if (vid.video == undefined){
//DO STUFF HERE - Doesn't work
}
The "object" in the screenshot is referenced in the code above as variable vid. I also tried undefined in the conditional.
I see some misunderstading here:
You say when an object property's value is blank but your coded if (vid.video != ""){.
I think you need if (!vid.video) {
use this:
vid.video == undefined
Also what Andrew said. If you want to DO STUFF when the attribute is empty, you should Use "==", and not "!="
if(vid.video != "")
Are you looking to only execute code when video doesn't equal "" but if you want to execute code when it is equal to "" you need
if(vid.video == "")
However if you want to check to see if its undefined you'll need to do
if(vid.video === undefined){
vid.video is not defined here
}
or
if(vid.video){
vid.video is defined here
}

Javascript only checks one field

Ok so I've been stumped on this one for days and its frustrating me. (Will frustrate me even more if it's something simple I'm overlooking).
I have a form generated in PHP which I want to verify that certain pieces are filled out. I do this via a JavaScript check when the user clicks the submit button.The JavaScript code is below:
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value == '' || document.getElementById('uname').value == ''
|| document.getElementById('sdescription').value == '' || document.getElementById('email').value == ''
|| document.getElementById('platf').value == "Select Group" || document.getElementByID('cate').value == "Select Category" )
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
For some reason though this only checks the ldescription field. If that field has text but all the others are empty it carries on like everything was filled out. Also if I change the order of my checks and ldescription is anywhere but the first check, it will do no check whatsoever even when all the fields are empty.
Any ideas?
EDIT:
Got it fixed. Along with the suggestion I marked as correct the document.getElementById('item').value command worked with only textarea boxes but not regular text input boxes. By changing the command to document.MyForm.myTextName.value everything fell into place.
Couple of problems i noticed with your sample code.
The last getElementById call has improper casing. The final d is capitalized and it shouldn't be
Comparing the value to a string literal should be done by === not ==.
JSLint complains there are line break issues in your if statement by having the line begin with || instead of having the previous line end with ||.
The first and third items are most likely the ones causing your problem.
Inside your if condition, when you are breaking a line, make sure that the last token in the line is the OR operator ||.
Javascript does semicolon insertion, so it may be that semicolons are being inserted (automatically, invisibly, by the interpreter) in a bad place.
Try the below code
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value === '' ||
document.getElementById('uname').value === '' ||
document.getElementById('sdescription').value === '' ||
document.getElementById('email').value === '' ||
document.getElementById('platf').value === "Select Group" ||
document.getElementById('cate').value === "Select Category")
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
Please use Javascript && operator which returns true if both the elements are true. || operator evaluates to true in case atleast one of the element is true which is what is happening in your case. You can take a look at Javascript boolean Logic

Categories

Resources