0

This is how input is set up:

input type="number" ng-model="yourNum" placeholder="Enter a number here"

I want to now parse this numerical input and perform the modulo function on it, and then print a statement.

I know I can use the modulo function, I'm wondering how to print statements based on the result. Ex: if (yourNum % 3 == 0) print "hello"

I'm having trouble using ng-if

2 Answers 2

1

If you want the content to be completely remove from the DOM when your conditional statement is true you can utilize the ngIf directive to conditionally include bits of HTML

<span ng-if="yourNum % 3 === 0">hello<span>

Or if you want it to always be there just hidden from the user you can use ng-show

<span ng-show="yourNum % 3 === 0">hello<span>

JS does some auto type conversion for you so in this instance the comparison will work. Search for js auto type conversion if you want some more info on it.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <input type="number" ng-model="yourNum" placeholder="Enter a number here">
  <span ng-if="yourNum % 3 === 0">yo</span> 
  <span ng-if="yourNum % 4 === 0">hello</span> 
</div>

Sign up to request clarification or add additional context in comments.

6 Comments

Pardon the confusion - I'm really new to all this so my question is going to sound a bit dumb. When I run the program using ng-show // ng-if, the html is not conditionally there - it's there from the outset. Even before I enter an input, "hello" shows up. What am I doing incorrectly here?
You have to properly close tags for the conditions to work. In the code you had in the comment before you were not closing the span tag </span>
that comment was a little premature, here's the actual code I'm using right now: puu.sh/lyC8G/8a3c05eab1.png (it's just hard formatting code in comments)
Do you have ng-app on the html tag? if it's on the head tag odd behavior will happen. I've added a working code snippet if that helps.
I tried replacing my code with yours and still same problem: puu.sh/lyCt4/3a35512d7b.png Here's the code: puu.sh/lyCqk/c9b65aa0ce.png
|
0

HTML:

<input type="number" ng-change="onNumberChange()" ng-model="yourNum" />
<p>{{ error }}</p>

Java Script:

$scope.onNumberChange = function () {
    $scope.error = $scope.yourNum%3 === 0 ? 'some error' : '';
}

Example

2 Comments

Thanks for the help! However, I need to do it in angularjs
Interesting. Thanks for the help, clearly I was wrong! Much appreciated :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.