add decimal point and thousand separator in to textbox - javascript

I am tying to add thousand separator and decimal point to my text box.
I am using below directive also
.directive('format', function ($filter) {
'use strict';
return {
require: '?ngModel',
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) {
return;
}
ctrl.$formatters.unshift(function () {
return $filter('number')(ctrl.$modelValue);
});
ctrl.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[\,\.]/g, ''),
b = $filter('number')(plainNumber);
elem.val(b);
return plainNumber;
});
}
};
})
this is my Demo
i need to modify this.
When user enter 500,000, it should be like 500,000.00
and user can be enter 5000.50 also.
How i modify this, can u help

Take the decimal placement out of the users control.
num = 599993863737
num = str(num).replace('.','')
num = float(num[:len(num)-2]+'.'+num[-2:])
print(num)
5999938637.37

You can use toFixed() and regex
function currency(el){
a = parseFloat(el.value);
a = a.toFixed(2);
a=a.toString();
var b = a.replace(/[^\d\.]/g,'');
var dump = b.split('.');
var c = '';
var lengthchar = dump[0].length;
var j = 0;
for (var i = lengthchar; i > 0; i--) {
j = j + 1;
if (((j % 3) == 1) && (j != 1)) {
c = dump[0].substr(i-1,1) + ',' + c;
} else {
c = dump[0].substr(i-1,1) + c;
}
}
if(dump.length>1){
if(dump[1].length>0){
c += '.'+dump[1];
}else{
c += '.';
}
}
console.log(c);
}
<input type='text' onkeyup='currency(this)'>

Related

How to stop Jquery function from running?

Newbie here. Probably because I'm already sleepy and can't find a solution. I'm trying to stop a function when I click on another button.
Here's the code so far:
When I click on a button (.start), it runs a function that messes up the text randomly without finish. But then, I want to click on button #stop and stop that specific function from running. I've tried toggles, preventDefault, event.stopPropagation(), setInterval, etc... None of them works. I've tried putting inside my function and outside as well.
Here's the current js code:
$(".start").click(function(){
var getTextNodesIn = function(el) {
// Look at all the page elements and returns the text nodes
return $(el)
.find(":not(iframe,script)")
.addBack()
.contents()
.filter(function() {
return this.nodeType == 3; // Text node types are type 3
});
};
// var textNodes = getTextNodesIn($("p, h1, h2, h3","*"));
var textNodes = getTextNodesIn($("p"));
function isLetter(char) {
return /^[\d]$/.test(char);
}
var wordsInTextNodes = [];
for (var i = 0; i < textNodes.length; i++) {
var node = textNodes[i];
var words = [];
var re = /\w+/g;
var match;
while ((match = re.exec(node.nodeValue)) != null) {
var word = match[0];
var position = match.index;
words.push({
length: word.length,
position: position
});
}
wordsInTextNodes[i] = words;
}
function messUpWords() {
for (var i = 0; i < textNodes.length; i++) {
var node = textNodes[i];
for (var j = 0; j < wordsInTextNodes[i].length; j++) {
// Only change a tenth of the words each round.
if (Math.random() > 1 / 10) {
continue;
}
var wordMeta = wordsInTextNodes[i][j];
var word = node.nodeValue.slice(
wordMeta.position,
wordMeta.position + wordMeta.length
);
var before = node.nodeValue.slice(0, wordMeta.position);
var after = node.nodeValue.slice(wordMeta.position + wordMeta.length);
node.nodeValue = before + messUpWord(word) + after;
}
}
}
function messUpWord(word) {
if (word.length < 3) {
return word;
}
return word[0] + messUpMessyPart(word.slice(1, -1)) + word[word.length - 1];
}
function messUpMessyPart(messyPart) {
if (messyPart.length < 2) {
return messyPart;
}
var a, b;
while (!(a < b)) {
a = getRandomInt(0, messyPart.length - 1);
b = getRandomInt(0, messyPart.length - 1);
}
return (
messyPart.slice(0, a) +
messyPart[b] +
messyPart.slice(a + 1, b) +
messyPart[a] +
messyPart.slice(b + 1)
);
}
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
setInterval(messUpWords, 50);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="controls pt-5">
<button class="start">Simulate</button>
<button id="stop">Stop</button>
</div>
<br>
<br>
<br>
<div>
<h1>Trying</h1>
<p>Friends who have dyslexia described to me how they experience reading. She <em>can</em> read, but it takes a lot of concentration, and the letters seems to "jump around".</p>
</div>
The function works pretty well. I'm just having a hard time making another button stop this function from running... Any help would be appreciated and I wish y'all a nice week.
You cannot stop a function from running because only one function can ever run at a time within the JavaScript runtime environment (single-threaded). When you click the button to try to stop the first function, what actually happens is that the first function finishes and then the click event associated with the button runs. And, by then, the first function has completed, so it's too late to stop it.
You can look into asynchronous operations, which run outside of the JavaScript runtime. In your case, using setInterval() to run a function repeatedly at regular intervals would probably be the best way to go. This would allow you to check between invocations to see if something else has occurred, which should stop the function from running at the next interval.
Now, you are using the interval timer, but you aren't setting up a reference to it, so you can't tell it to stop when you need it to. The solution is to associate a variable with the timer and then to call clearInterval() and pass it the timer reference as shown here:
let timer = null; // This will hold a reference to the timer so you can stop it later
$("#stop").on("click", function(){
clearInterval(timer); // Stop the timer
});
$(".start").click(function(){
var getTextNodesIn = function(el) {
// Look at all the page elements and returns the text nodes
return $(el).find(":not(iframe,script)")
.addBack()
.contents()
.filter(function() {
return this.nodeType == 3; // Text node types are type 3
});
};
// var textNodes = getTextNodesIn($("p, h1, h2, h3","*"));
var textNodes = getTextNodesIn($("p"));
function isLetter(char) {
return /^[\d]$/.test(char);
}
var wordsInTextNodes = [];
for (var i = 0; i < textNodes.length; i++) {
var node = textNodes[i];
var words = [];
var re = /\w+/g;
var match;
while ((match = re.exec(node.nodeValue)) != null) {
var word = match[0];
var position = match.index;
words.push({
length: word.length,
position: position
});
}
wordsInTextNodes[i] = words;
}
function messUpWords() {
for (var i = 0; i < textNodes.length; i++) {
var node = textNodes[i];
for (var j = 0; j < wordsInTextNodes[i].length; j++) {
// Only change a tenth of the words each round.
if (Math.random() > 1 / 10) {
continue;
}
var wordMeta = wordsInTextNodes[i][j];
var word = node.nodeValue.slice(
wordMeta.position,
wordMeta.position + wordMeta.length
);
var before = node.nodeValue.slice(0, wordMeta.position);
var after = node.nodeValue.slice(wordMeta.position + wordMeta.length);
node.nodeValue = before + messUpWord(word) + after;
}
}
}
function messUpWord(word) {
if (word.length < 3) {
return word;
}
return word[0] + messUpMessyPart(word.slice(1, -1)) + word[word.length - 1];
}
function messUpMessyPart(messyPart) {
if (messyPart.length < 2) {
return messyPart;
}
var a, b;
while (!(a < b)) {
a = getRandomInt(0, messyPart.length - 1);
b = getRandomInt(0, messyPart.length - 1);
}
return (
messyPart.slice(0, a) +
messyPart[b] +
messyPart.slice(a + 1, b) +
messyPart[a] +
messyPart.slice(b + 1)
);
}
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
timer = setInterval(messUpWords, 50); // Set interval reference to variable
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="controls pt-5">
<button class="start">Simulate</button>
<button id="stop">Stop</button>
</div>
<br>
<br>
<br>
<div>
<h1>Trying</h1>
<p>Friends who have dyslexia described to me how they experience reading. She <em>can</em> read, but it takes a lot of concentration, and the letters seems to "jump around".</p>
</div>
You can check at the top of the messUpWords function to see if the stop button has been clicked. If it has, you can clear the interval, reset the the stop button flag, and escape the routine.
var stopBtnClicked = false;
var stopBtn = document.getElementById("stop");
stopBtn.addEventListener("click", function() {
stopBtnClicked = true;
}, false);
$(".start").click(function() {
var getTextNodesIn = function(el) {
// Look at all the page elements and returns the text nodes
return $(el)
.find(":not(iframe,script)")
.addBack()
.contents()
.filter(function() {
return this.nodeType == 3; // Text node types are type 3
});
};
// var textNodes = getTextNodesIn($("p, h1, h2, h3","*"));
var textNodes = getTextNodesIn($("p"));
function isLetter(char) {
return /^[\d]$/.test(char);
}
var wordsInTextNodes = [];
for (var i = 0; i < textNodes.length; i++) {
var node = textNodes[i];
var words = [];
var re = /\w+/g;
var match;
while ((match = re.exec(node.nodeValue)) != null) {
var word = match[0];
var position = match.index;
words.push({
length: word.length,
position: position
});
}
wordsInTextNodes[i] = words;
}
function messUpWords() {
if (stopBtnClicked) {
clearInterval(jumbleTimer);
stopBtnClicked = false;
return;
}
for (var i = 0; i < textNodes.length; i++) {
var node = textNodes[i];
for (var j = 0; j < wordsInTextNodes[i].length; j++) {
// Only change a tenth of the words each round.
if (Math.random() > 1 / 10) {
continue;
}
var wordMeta = wordsInTextNodes[i][j];
var word = node.nodeValue.slice(
wordMeta.position,
wordMeta.position + wordMeta.length
);
var before = node.nodeValue.slice(0, wordMeta.position);
var after = node.nodeValue.slice(wordMeta.position + wordMeta.length);
node.nodeValue = before + messUpWord(word) + after;
}
}
}
function messUpWord(word) {
if (word.length < 3) {
return word;
}
return word[0] + messUpMessyPart(word.slice(1, -1)) + word[word.length - 1];
}
function messUpMessyPart(messyPart) {
if (messyPart.length < 2) {
return messyPart;
}
var a, b;
while (!(a < b)) {
a = getRandomInt(0, messyPart.length - 1);
b = getRandomInt(0, messyPart.length - 1);
}
return (
messyPart.slice(0, a) +
messyPart[b] +
messyPart.slice(a + 1, b) +
messyPart[a] +
messyPart.slice(b + 1)
);
}
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
var jumbleTimer = setInterval(messUpWords, 50);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="controls pt-5">
<button class="start">Simulate</button>
<button id="stop">Stop</button>
</div>
<br>
<br>
<br>
<div>
<h1>Trying</h1>
<p>Friends who have dyslexia described to me how they experience reading. She <em>can</em> read, but it takes a lot of concentration, and the letters seems to "jump around".</p>
</div>

Expansion of algebraic term

I am trying to expand an algebraic term.
(x+1)(x+1)/x => x + 2 + x^-1
(x+1)^3 => x^3 + 3x^2 + 3x + 1
(x^2*x)(x^2) => x^5
This is my attempt at it. I have tried a lot of ways trying to fix the problems below.
Problems:
Like terms should be added together
(x+1)(x+1)(x+1) should be valid.
(x+1)^2 should be equal to (x+1)(x+1)
x(x+1) should be valid
1x^n should just be x^n
There should be no 0x^n terms.
nx^0 terms should just be n
Code Snippet:
function split(input) {
return ((((input.split(")(")).toString()).replace(/\)/g, "")).replace(/\(/g, "")).split(','); }
function strVali(str) {
str = str.replace(/\s+/g, "");
var parts = str.match(/[+\-]?[^+\-]+/g);
// accumulate the results
return parts.reduce(function(res, part) {
var coef = parseFloat(part) || +(part[0] + "1") || 1;
var x = part.indexOf('x');
var power = x === -1 ?
0:
part[x + 1] === "^" ?
+part.slice(x + 2) :
1;
res[power] = (res[power] || 0) + coef;
return res;
}, {});
}
function getCoeff(coeff) {
var powers = Object.keys(strVali(coeff));
var max = Math.max.apply(null, powers);
var result = [];
for(var i = max; i >= 0; i--)
result.push(strVali(coeff)[i] || 0);
return result; }
function evaluate(expression) {
var term1 = getCoeff(expression[0]);
var term2 = getCoeff(expression[1]);
var expand = "";
for ( var j = 0; j < term1.length; j++ ) {
for ( var i = 0; i < term2.length; i++ ) {
expand += Number(term1[j] * term2[i]) + 'x^ ' + (Number(term1.length) - 1 - j + Number(term2.length) - 1 - i) + ' + ';
}}
var final = "";
for ( var Z = 0; Z < getCoeff(expand).length; Z++) {
final += ' ' + getCoeff(expand)[Z] + 'x^ {' + (getCoeff(expand).length - Z - 1) + '} +';
}
final = "$$" + ((((((final.replace(/\+[^\d]0x\^ \{[\d]+\}/g,'')).replace(/x\^ \{0}/g,'')).replace(/x\^ \{1}/g,'x')).replace(/[^\d]1x\^ /g,'+ x^')).replace(/\+ -/g,' - ')).slice(0, -1)).substring(1,(final.length)) + "$$";
document.getElementById('result').innerHTML = final;
MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById('result')]);
}
function caller() {
var input = document.getElementById('input').value;
evaluate(split(input)); }
div.wrapper {
width: 100%;
height:100%;
border:0px solid black;
}
input[type="text"] {
display: block;
margin : 0 auto;
padding: 10px;
font-size:20px;
}
button{
margin:auto;
display:block;
background-color: white;
color: black;
border: 2px solid #555555;
padding-left: 20px;
padding-right: 20px;
font-size: 20px;
margin-top:10px;
}
button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<div class='wrapper'><input id="input" title="Enter Expression" type="text" value="(x^2+x+1)(x^2+x+1)"></div>
<div> <button onclick="caller()">Click</button></div>
<div id="result">$$x^4 + 2x^3 + 3x^2 + 2x + 1$$</div>
Reference:
How to calculate coefficients of polynomial expansion in javascript
Getting coefficients of algebraic term
How to get a term before a character?
Edit: I have re-written my original answer from when the question did not include the - and / operators). My new answer supports - and /.
Since you have not defined a precise grammar, I have made some assumptions. I support the +, -, /, ^ operators and the implicit multiply. These can operate on numbers, x and (...) expressions, except that right hand side of the ^ operator must be a number. I allow spaces between tokens.
Limitations: The -is a binary not unary - operator, So x-2 if OK, -2 on its own is a syntax error. The / is limited. You may divide by a value with a single coefficient such as 2, 'x', 2x^2, but not by cannot have 1/(x^2+1), which would evaluate to an infinite series.
It first takes the string and wraps it in a 'tokenizer' which lets you look it one token at a time, where a token is a number, x, ( ) or operator.
It then calls evaluateSum() which evaluates things separated by + or -, where each thing is a product evaluated by evaluateProduct(). This in turn uses evaluatePower() to evalue the ^. Finally evaluateTerm() looks for x, numbers and bracketed sub-expressions which are evaluates recursively with evaluateSum(). This hierarchy creates the correct operator precedence and evaluation order.
Each layer of the evaluation returns a 'coefficients' object which s array-like, but may contain megative indexes. For example [1,0,1] means 1+x^2.
It can cope with any number of nested brackets and a lot of other case such as xx(x) is x^3, 2^3 is 8. I have added a few throws for syntax errors, for example 2^x is illegal.
function makeTokenizer(source) {
var c, i, tokenizer;
i = 0; // The index of the current character.
c = source.charAt(i); // The current character.
function consumeChar() { // Move to next c, return previous c.
var prevC = c;
i += 1;
c = source.charAt(i);
return prevC;
}
tokenizer = {
next : function () {
var str;
while (c === ' ') { // Skip spaces
consumeChar();
}
if (!c) {
tokenizer.token = undefined; // End of source
} else if (c >= '0' && c <= '9') { // number
str = consumeChar(); // First digit
while (c >= '0' && c <= '9') { // Look for more digits.
str += consumeChar();
}
tokenizer.token = Number(str);
} else if (c === "x") {
tokenizer.token = consumeChar();
} else { // single-character operator
tokenizer.token = consumeChar();
}
}
};
tokenizer.next(); // Load first token.
return tokenizer;
}
function makeCoefficients() { // Make like an array but can have -ve indexes
var min = 0, max = 0, c = {};
return {
get: function (i) {
return c[i] || 0;
},
set: function (i, value) {
c[i] = value;
min = Math.min(i, min);
max = Math.max(i + 1, max);
return this; // for chaining
},
forEach: function (callback) {
var i;
for (i = min; i < max; i += 1) {
if (this.get(i)) {
callback(this.get(i), i);
}
}
},
toString: function () {
var result = "", first = true;
this.forEach(function (val, power) {
result += (val < 0 || first) ? "" : "+";
first = false;
result += (val === 1 && power !== 0) ? "" : val;
if (power) {
result += "x";
if (power !== 1) {
result += "^" + power;
}
}
});
return result;
},
toPowerOf: function (power) {
if (power === 0) {
return makeCoefficients().set(0, 1); // Anything ^0 = 1
}
if (power === 1) {
return this;
}
if (power < 0) {
throw "cannot raise to negative powers";
}
return this.multiply(this.toPowerOf(power - 1));
},
multiply: function (coefficients) {
var result = makeCoefficients();
this.forEach(function (a, i) {
coefficients.forEach(function (b, j) {
result.set(i + j, result.get(i + j) + a * b);
});
});
return result;
},
divide: function (coefficients) {
// Division is hard, for example we cannot do infinite series like:
// 1/(1 + x^2) = sum_(n=0 to infinity) 1/2 x^n ((-i)^n + i^n)
// So we do a few easy cases only.
var that = this, result = makeCoefficients(), done;
coefficients.forEach(function (value, pow) {
that.forEach(function (value2, pow2) {
result.set(pow2 - pow, value2 / value);
});
if (done) {
throw "cannot divide by " + coefficients.toString();
}
done = true;
});
return result;
},
add: function (coefficients, op) {
var result = makeCoefficients();
this.forEach(function (value, i) {
result.set(value, i);
});
op = (op === "-" ? -1 : 1);
coefficients.forEach(function (value, i) {
result.set(i, result.get(i) + value * op);
});
return result;
}
};
}
var evaluateSum; // Called recursively
function evaluateTerm(tokenizer) {
var result;
if (tokenizer.token === "(") {
tokenizer.next();
result = evaluateSum(tokenizer);
if (tokenizer.token !== ")") {
throw ") missing";
}
tokenizer.next();
} else if (typeof tokenizer.token === "number") {
result = makeCoefficients().set(0, tokenizer.token);
tokenizer.next();
} else if (tokenizer.token === "x") {
tokenizer.next();
result = makeCoefficients().set(1, 1); // x^1
} else {
return false; // Not a 'term'
}
return result;
}
function evaluatePower(tokenizer) {
var result;
result = evaluateTerm(tokenizer);
if (tokenizer.token === "^") {
tokenizer.next();
if (typeof tokenizer.token !== "number") {
throw "number expected after ^";
}
result = result.toPowerOf(tokenizer.token);
tokenizer.next();
}
return result;
}
function evaluateProduct(tokenizer) {
var result, term, divOp;
result = evaluatePower(tokenizer);
if (!result) {
throw "Term not found";
}
while (true) {
divOp = (tokenizer.token === "/");
if (divOp) {
tokenizer.next();
term = evaluatePower(tokenizer);
result = result.divide(term);
} else {
term = evaluatePower(tokenizer);
if (!term) {
break;
}
result = result.multiply(term);
}
}
return result;
}
function evaluateSum(tokenizer) {
var result, op;
result = evaluateProduct(tokenizer);
while (tokenizer.token === "+" || tokenizer.token === "-") {
op = tokenizer.token;
tokenizer.next();
result = result.add(evaluateProduct(tokenizer), op);
}
return result;
}
function evaluate(source) {
var tokenizer = makeTokenizer(source),
coefficients = evaluateSum(tokenizer);
if (tokenizer.token) {
throw "Unexpected token " + tokenizer.token;
}
console.log(source + " => " + coefficients.toString());
}
// Examples:
evaluate("(x+1)(x+1)"); // => 1+2x+x^2
evaluate("(x+1)^2"); // => 1+2x+x^2
evaluate("(x+1)(x+1)(x+1)"); // => 1+3x+3x^2+x^3
evaluate("(x+1)^3"); // => 1+3x+3x^2+x^3
evaluate("(x)(x+1)"); // => x+x^2
evaluate("(x+1)(x)"); // => x+x^2
evaluate("3x^0"); // => 3
evaluate("2^3"); // => 8
evaluate("(x+2x(x+2(x+1)x))"); // => x+6x^2+4x^3
evaluate("(x+1)(x-1)"); // => -1+x^2
evaluate("(x+1)(x+1)/x"); // x^-1+2+x
//evaluate("(x+1)/(x^2 + 1)"); //throws cannot divide by 1+2x
It can handle +, -, / and implicit multiplication. It expands the parenthesis accordingly and adds them to the original expression while removing the parenthesised version. It collects like terms accordingly. Limitations: It cannot divide by a polynomial and it does not support the * operator.
function strVali(str) {
str = str.replace(/\s+/g, "");
var parts = str.match(/[+\-]?[^+\-]+/g);
return parts.reduce(function(res, part) {
var coef = parseFloat(part) || +(part[0] + "1") || 1;
var x = part.indexOf('x');
var power = x === -1 ?
0:
part[x + 1] === "^" ?
+part.slice(x + 2) :
1;
res[power] = (res[power] || 0) + coef;
return res;
}, {});
}
function getCoeff(coeff) {
var powers = Object.keys(strVali(coeff));
var max = Math.max.apply(null, powers);
var result = [];
for(var i = max; i >= 0; i--)
result.push(strVali(coeff)[i] || 0);
return result; }
function format(str) {
str = ' ' + str;
str = str.replace(/-/g,'+-').replace(/x(?!\^)/g,'x^1').replace(/([+\/*)(])(\d+)([+\/*)(])/g,'$1$2x^0$3').replace(/([^\d])(x\^-?\d+)/g,'$11$2').replace(/(-?\d+x\^\d+)(?=\()/g,'($1)').replace(/(\))(-?\d+x\^\d+)/g,'$1($2)').replace(/([^\)\/])(\()([^\*\/\(\)]+?)(\))(?![(^\/])/g,'$1$3');
str = str.replace(/(\([^\(\)]+?\))\/(\d+x\^-?\d+)/g,'$1/($2)').replace(/(\d+x\^-?\d+)\/(\d+x\^-?\d+)/g,'($1)/($2)').replace(/(\d+x\^-?\d+)\/(\(\d+x\^-?\d+\))/g,'($1)/$2');
return str;
}
function expBrackets(str) {
var repeats = str.match(/\([^\(\)]+?\)\^\d+/g);
if ( repeats === null ) { return str; } else { var totalRepeat = '';
for ( var t = 0; t < repeats.length; t++ ) { var repeat = repeats[t].match(/\d+$/); for ( var u = 0; u < Number(repeat); u++ ) { totalRepeat += repeats[t].replace(/\^\d+$/,''); }
str = str.replace(/\([^\(\)]+?\)\^\d+/, totalRepeat); totalRepeat = ''; }
return str; }
}
function multiply(str) {
var pairs = str.match(/\([^\(\)]+?\)\([^\(\)]+?\)/g);
if ( pairs !== null ) { while ( pairs !== null ) { var output = '';
for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].slice(1).slice(0, -1).split(')('); var firstCoeff = getCoeff(pair[0]); var secondCoeff = getCoeff(pair[1]);
for (var j = 0; j < firstCoeff.length; j++) {
for (var k = 0; k < secondCoeff.length; k++) { output += firstCoeff[j] * secondCoeff[k] + 'x^' + Number(firstCoeff.length - 1 - j + secondCoeff.length - 1 - k) + '+'; } }
var regexp = new RegExp(pairs[i].replace(/\(/g,'\\(').replace(/\+/g,'\\+').replace(/\)/g,'\\)').replace(/\^/g,'\\^').replace(/\-/g,'\\-'));
str = str.replace(regexp, '(' + (output.slice(0, -1).replace(/[^\d]0x\^\d+/g,'')) + ')');
output = ''; }
pairs = str.match(/\([^\(\)]+?\)\([^\(\)]+?\)/g); } }
else { }
str = str.replace(/\+/g,' + ');
return str;
}
function divide(str) {
if ( str.match(/\/(\(-?\d+x\^-?\d+.+?\))/g) === null && str.match(/\//g) !== null ) {
while ( pairs !== null ) {
var pairs = str.match(/\([^\(\)]+?\)\/\([^\(\)]+?\)/g);
var output = '';
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].slice(1).slice(0, -1).split(')/(');
var firstCoeff = getCoeff(pair[0]);
var secondCoeff = getCoeff(pair[1]);
for (var j = 0; j < firstCoeff.length; j++) {
for (var k = 0; k < secondCoeff.length; k++) {
output += firstCoeff[j] / secondCoeff[k] + 'x^' + Number(firstCoeff.length - 1 - j - secondCoeff.length + 1 + k) + '+';
output = output.replace(/([+-])Infinityx\^\-?\d+/g,'').replace(/([+-])NaNx\^\-?\d+/g,'');
} }
var regexp = new RegExp(pairs[i].replace(/\(/g,'\\(').replace(/\+/g,'\\+').replace(/\)/g,'\\)').replace(/\^/g,'\\^').replace(/\-/g,'\\-'));
str = str.replace(regexp, '(' + (output.slice(0, -1).replace(/[^\d]0x\^-?\d+/g,'')) + ')');
output = ''; }
pairs = str.match(/\([^\(\)]+?\)\/\([^\(\)]+?\)/g); } }
else { }
return str;
}
function evaluate(str) {
var result = format(divide(format(multiply(expBrackets(format((str)))))));
var resultCollect = '';
result = result.replace(/\s+/g, "").replace(/[^\d]0x\^-?\d+/g,'').replace(/\+/g,' + ');
if ( result === '') {
document.getElementById('result').innerHTML = '$$' + str + '$$' + '$$ = 0 $$';
MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById('result')]);
} else if ( result.match(/-?\d+x\^-\d+/g) === null && str.match(/\/(\(-?\d+x\^-?\d+.+?\))/g) === null) {
for ( var i = 0; i < getCoeff(result).length; i++ ) {
resultCollect += getCoeff(result)[i] + 'x^' + Number(getCoeff(result).length - 1 - i) + '+' ; }
if ( resultCollect !== '')
resultCollect = '$$ = ' + resultCollect.slice(0,-1).replace(/[^\d]0x\^-?\d+/g,'').replace(/\+/g,' + ').replace(/x\^0/g,'').replace(/x\^1(?!\d+)/g,'x').replace(/\^(-?\d+)/g,'\^\{$1\}').replace(/\+ -/g,' - ') + '$$';
else
resultCollect = 'Error: Trying to divide by a polynomial ';
document.getElementById('result').innerHTML = '$$' + str.replace(/\^(-?\d+)/g,'\^\{$1\}') + '$$' + resultCollect;
MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById('result')]);
} else {
resultCollect = '$$ = ' + result.replace(/\^(-?\d+)/g,'\^\{$1\}') + '$$';
document.getElementById('result').innerHTML = '$$' + str.replace(/\^(-?\d+)/g,'\^\{$1\}').replace(/\+ -/g,' - ') + '$$' + resultCollect;
MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById('result')]);
}
}
function caller() {
var input = document.getElementById('input').value;
evaluate(input);
}
div.wrapper {
width: 100%;
height:100%;
border:0 solid black;
}
input[type="text"] {
display: block;
margin : 0 auto;
padding: 10px;
font-size:20px;
}
button{
margin:auto;
display:block;
background-color: white;
color: black;
border: 2px solid #555555;
padding-left: 20px;
padding-right: 20px;
font-size: 20px;
margin-top:10px;
}
button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<input id="input" type="text" title="Enter Expression: ">
<button onclick="caller()">Click</button>
<div id="result"></div>
<div id="errors"></div>
My approach utilizes two helper classes:
-Term: This stores a coefficient and an object, the keys of which are variables and the values of which are the exponents. It has methods for determining whether terms are the "same" (i.e. whether they have the same variables with the same exponents, thus allowing them to be added), adding terms, and multiplying terms.
-Polynomial: This stores an array of terms. It has methods for adding two polynomials, multiplying two polynomials, and simplifying polynomials (eliminating terms with 0 coefficients and combining like terms).
It has two substantial helper functions:
-findOuterParens - Given a string, this function returns the indices of the first outermost pair of left and right parentheses.
-parseExpressionStr - This function uses a regular expression to split a string into three types of substrings: 1) a number, 2) a symbol (i.e. a variable, like 'x' or 'y'), or 3) an operator (*, -, +, ^, /). It creates Polynomial objects for the first two types and leaves the operators as strings.
The expand function runs the show. It takes in a string and returns a Polynomial object representing the expanded form of the polynomial in the string. It does this as follows:
1) It deals with parentheses by recursion. It uses findOuterParens to find all outermost parenthsized substrings. So for "3x*(x+4)+(2(y+1))*t", for instance, it would find "x+4" and "2(y+1)" as parenthsized substrings. It then passes these to itself for further parsing. For "2(y+1)", it would identify "y+1" as a parenthesized substring, and pass this to itself, for three levels of recursion for this example.
2) It deals with other parts of the string using parseExpressionStr. After steps 1 and 2, it has an array containing Polynomial objects and operators (stored as strings). It then proceeds to simplifying and expanding.
3) It converts subtraction subproblems to addition subproblems by replacing all -'s with +'s and multiplying all polynomials following -'s by -1.
4) It converts division subproblems to multiplication subproblems by replacing /'s with *'s and inverting the Polynomial following the /. If the polynomial following the / has more than one term, it throws an error.
5) It converts power subproblems to multiplication subproblems by replacing ^'s with a series of multiplications.
6) It adds in implicit *'s. I.e. if two Polynomial elements are right next to each other in the array, then it's inferred that they are being multiplied, so, e.g. '2*x' == '2x'.
7) Now the array has polynomial objects alternating with either '+' or '*'. It first performs all polynomial multiplications and then performs all additions.
8) It performs a final simplification step and returns the resulting expanded polynomial.
<html>
<head></head>
<body></body>
<script>
function findOuterParens(str) {
var leftIndex = str.indexOf('('), leftNum = 1, rightNum = 0;
if (leftIndex === -1)
return
for (var i=leftIndex+1; i<str.length; i++) {
if (str[i] === '(')
leftNum++;
else if (str[i] === ')')
rightNum++, rightIndex=i;
if (leftNum === rightNum)
return {start: leftIndex, end: rightIndex}
}
throw Error('Parenthesis at position ' + leftIndex + ' of "' + str + '" is unpaired.');
}
function parseExpressionStr(inputString) {
var result = [], str = inputString;
while (str) {
var nextPart = str.match(/([\d]+)|([\+\-\^\*\/])|([a-zA-z])/);
if (!nextPart)
return result;
if (nextPart.length === 0)
throw Error('Unable to parse expression string "' + inputString + '". Remainder "' + str + '" could not be parsed.');
else if (nextPart[1]) // First group (digits) matched
result.push(new Polynomial(parseFloat(nextPart[0])));
else if (nextPart[3]) // Third group (symbol) matched
result.push(new Polynomial(nextPart[0]));
else // Second group (operator) matched
result.push(nextPart[0]);
str = str.substring(nextPart.index+nextPart[0].length);
}
return result
}
function isOperator(char) {
return char === '*' || char === '/' || char === '^' || char === '+' || char === '-';
}
function Polynomial(value) {
this.terms = (value!==undefined) ? [new Term(value)] : [];
}
Polynomial.prototype.simplify = function() {
for (var i=0; i<this.terms.length-1; i++) {
if (this.terms[i].coeff === 0) {
this.terms.splice(i--, 1);
continue;
}
for (var j=i+1; j<this.terms.length; j++) {
if (Term.same(this.terms[i], this.terms[j])) {
this.terms[i] = Term.add(this.terms[i], this.terms[j]);
this.terms.splice(j--, 1);
}
}
}
}
Polynomial.add = function(a, b) {
var result = new Polynomial();
result.terms = a.terms.concat(b.terms);
result.simplify();
return result
}
Polynomial.multiply = function(a, b) {
var result = new Polynomial();
a.terms.forEach(function(aTerm) {
b.terms.forEach(function (bTerm) {
result.terms.push(Term.multiply(aTerm, bTerm));
});
});
result.simplify();
return result
}
Polynomial.prototype.toHtml = function() {
var html = ''
for (var i=0; i<this.terms.length; i++) {
var term = this.terms[i];
if (i !== 0)
html += (term.coeff < 0) ? ' - ' : ' + ';
else
html += (term.coeff < 0) ? '-' : '';
var coeff = Math.abs(term.coeff);
html += (coeff === 1 && Object.keys(term.symbols).length > 0) ? '' : coeff;
for (var symbol in term.symbols) {
var exp = term.symbols[symbol];
exp = (exp !== 1) ? exp : '';
html += symbol + '<sup>' + exp + '</sup>';
}
}
return html;
}
function Term(value) {
this.symbols = {};
if (typeof value==='string') { // Symbol
this.symbols[value] = 1;
this.coeff = 1;
} else if (typeof value==='number') { // Number
this.coeff = value;
} else {
this.coeff = 1;
}
}
Term.same = function(a, b) {
if (Object.keys(a.symbols).length != Object.keys(b.symbols).length)
return false
else
for (var aSymbol in a.symbols)
if (a.symbols[aSymbol] != b.symbols[aSymbol]) return false
return true
}
Term.add = function(a, b) {
var result = new Term();
Object.assign(result.symbols, a.symbols);
result.coeff = a.coeff + b.coeff;
return result
}
Term.multiply = function(a, b) {
var result = new Term();
Object.assign(result.symbols, a.symbols);
for (var symbol in b.symbols) {
if (!(symbol in result.symbols))
result.symbols[symbol] = 0;
result.symbols[symbol] += b.symbols[symbol];
if (result.symbols[symbol] === 0)
delete result.symbols[symbol];
}
result.coeff = a.coeff * b.coeff;
return result
}
function expand(str) {
var result = [];
var parens = findOuterParens(str);
while (parens) {
result = result.concat(parseExpressionStr(str.slice(0,parens.start)));
result.push(expand(str.slice(parens.start+1, parens.end)))
str = str.slice(parens.end+1);
parens = findOuterParens(str);
}
result = result.concat(parseExpressionStr(str));
// Move -s to coefficients
var minus = result.indexOf('-'), minusPoly = new Polynomial(-1);
while (minus !== -1) {
result[minus] = '+';
result[minus+1] = Polynomial.multiply(minusPoly, result[minus+1]);
minus = result.indexOf('-');
}
// Get rid of +s that follow another operator
var plus = result.indexOf('+');
while (plus !== -1) {
if (plus===0 || isOperator(result[plus-1])) {
result.splice(plus--, 1);
}
plus = result.indexOf('+', plus+1);
}
// Convert /s to *s
var divide = result.indexOf('/');
while (divide !== -1) {
result[divide] = '*';
var termsToInvert = result[divide+1].terms;
if (termsToInvert.length > 1)
throw Error('Attempt to divide by a polynomial with more than one term.');
var termToInvert = termsToInvert[0];
for (var symbol in termToInvert.symbols) {
termToInvert.symbols[symbol] = -termToInvert.symbols[symbol];
}
termToInvert.coeff = 1/termToInvert.coeff;
divide = result.indexOf('/');
}
// Convert ^s to *s
var power = result.indexOf('^');
while (power !== -1) {
var exp = result[power+1];
if (exp.terms.length > 1 || Object.keys(exp.terms[0].symbols).length != 0)
throw Error('Attempt to use non-number as an exponent');
exp = exp.terms[0].coeff;
var base = result[power-1];
var expanded = [power-1, 3, base];
for (var i=0; i<exp-1; i++) {
expanded.push('*');
expanded.push(base);
}
result.splice.apply(result, expanded);
power = result.indexOf('^');
}
// Add implicit *s
for (var i=0; i<result.length-1; i++)
if (!isOperator(result[i]) && !(isOperator(result[i+1])))
result.splice(i+1, 0, '*');
// Multiply
var mult = result.indexOf('*');
while (mult !== -1) {
var product = Polynomial.multiply(result[mult-1], result[mult+1]);
result.splice(mult-1, 3, product);
mult = result.indexOf('*');
}
// Add
var add = result.indexOf('+');
while (add !== -1) {
var sum = Polynomial.add(result[add-1], result[add+1]);
result.splice(add-1, 3, sum);
add = result.indexOf('+');
}
result[0].simplify();
return result[0];
}
var problems = ['(x+1)(x+1)/x', '(x+1)^3', '(x^2*x)(x^2)', '(x+1)(x+1)(x+1)',
'(x+1)^2', 'x(x+1)', '1x^4', '(x + (x+2))(x+5)', '3x^0', '2^3',
'(x+2x(x+2(x+1)x))', '(x+1)(x-1)', '(x+1)(y+1)', '(x+y+t)(q+x+7)'];
var solutionHTML = '';
for (var i = 0; i<problems.length; i++) {
solutionHTML += problems[i] + ' => ' + expand(problems[i]).toHtml() + '<br>';
}
document.body.innerHTML = solutionHTML;
</script>
</html>
It outputs:

How to capitalize first and third letter?

I want to capitalize first letter and third letter in my textarea.
I can capitalize only first letter and then every next letters and words are transformed to lowercase.
If there is any solution for this problem, please tell me.
I am using AngularJS.
This is what im trying and did.
link: function (scope, iElement, iAttrs, controller) {
//console.log('init');
controller.$parsers.push(function (inputValue) {
var transformedInput = (!!inputValue) ? inputValue.charAt(0).toUpperCase() + inputValue.substr(1).toLowerCase() : '';
if (transformedInput != inputValue) {
controller.$setViewValue(transformedInput);
controller.$render();
}
return transformedInput;
});
This works only for first letter, it transforms to uppercase and then transforms another letter and words to lowercase.
I tried to change my code into this but nothing.
var transformedInput = (!!inputValue) ? inputValue.charAt(0).toUpperCase() + inputValue.substr(1).toLowerCase() + inputValue.charAt(3).toUpperCase() + inputValue.substr(4).toLowerCase(): '';
Have a look at this. Same as what you are doing just using for loop to identify the character index to modify.
var inputValue = "test";
var transformedInput = '';
if(inputValue){
for(var i=0; i<inputValue.length; i++){
if(i===0 || i=== 2){
transformedInput += inputValue.charAt(i).toUpperCase();
} else {
transformedInput += inputValue.charAt(i).toLowerCase();
}
}
}
console.log(transformedInput);
Here is a function to capitalize chars at specific positions
function capitalizeAtPositions(string, indexes) {
(indexes || []).forEach(function(index) {
if (string.length < index) return;
string = string.slice(0, index) +
string.charAt(index).toUpperCase() + string.slice(index+1);
});
return string;
}
Run it as follows:
var test = "abcdefg";
var result = capitalizeAtPositions(test, [0, 2]);
//AbCdefg
In your case i think it will be something like (can't test it without jsfiddle):
var transformedInput = capitalizeAtPositions(inputValue || '', [0, 2]);
My simple solution
var inputValue = 'your value';
function toUpper (str) {
var result = '';
for (var i = 0; i < str.length; i++) {
if (i === 0 || i === 2) {
result += str[i].toUpperCase();
} else {
result += str[i].toLowerCase();
}
}
return result;
}
var transformedInput = toUpper(inputValue);
Seeing how you need to have the input change as you type, you'll probably need a directive; here's a one to capitalize the given letters of any input with an ng-model:
https://plnkr.co/edit/hWhmjQWdrghvsL20l3DE?p=preview
app.directive('myUppercase', function() {
return {
scope: {
positions: '=myUppercase'
},
require: 'ngModel',
link: function(scope, elem, attrs, ngModelCtrl) {
scope.positions = scope.positions || []
function makeString(string) {
if (!string) return;
angular.forEach(scope.positions, function(pos) {
string = string.slice(0, pos) + string.slice(pos, pos+1).toUpperCase() + string.slice(pos + 1)
console.log(string)
})
return string;
}
ngModelCtrl.$parsers.push(makeString)
ngModelCtrl.$formatters.push(makeString)
}
}
})
HTML:
<input ng-model="value" my-uppercase="[0, 2]">
My solution for "McArturo" this type of text you want
$("#LastName").keyup(function () {
var last_name = $("#LastName").val();
var op = last_name.substr(0, 2);
if (op == "mc" || op == "Mc" || op == "MC") {
$("#LastName").val("Mc" + (last_name.charAt(2).toUpperCase()) + last_name.substr(3).toLowerCase());
} else {
$("#LastName").val(last_name.charAt(0).toUpperCase() + last_name.substr(1).toLowerCase());
}});

Angular custom directive not setting value after promise resolve

I have a custom directive, it works great when user is entering value, the problem is when loading the form, the input field is not being rendered.
Here is my directive:
var cuitModule = angular.module('cuitModule', []).directive('cuitDirective', ['$filter', function ($filter) {
return {
require: '?ngModel',
link: link,
restrict: 'E',
scope: {
cuitPlaceholder: '=placeholder'
},
templateUrl: 'js/common/directives/cuit/cuit.directive.html'
};
/*
Intended use:
<cuit-directive placeholder='prompt' model='someModel.cuit'></cuit-directive>
Where:
someModel.cuit: {String} value which to bind only the numeric characters [0-9] entered
ie, if user enters 20-33452648-9, value of 20334526489 will be bound to model
prompt: {String} text to keep in placeholder when no numeric input entered
*/
function link(scope, element, attributes, ngModel) {
// scope.inputValue is the value of input element used in template
scope.inputValue = ngModel.$viewValue;
scope.$watch('inputValue', function (value, oldValue) {
value = String(value);
var number = value.replace(/[^0-9]+/g, '');
// scope.cuitModel = number;
scope.inputValue = $filter('cuit')(number);
var valid = validarCuit(number);
ngModel.$setValidity('required', valid);
if (valid) {
ngModel.$setViewValue(number);
}
});
//source https://es.wikipedia.org/wiki/Clave_%C3%9Anica_de_Identificaci%C3%B3n_Tributaria#C.C3.B3digo_Javascript
function validarCuit(cuit) {
if (cuit.length !== 11) {
return false;
}
var acumulado = 0;
var digitos = cuit.split('');
var digito = digitos.pop();
for (var i = 0; i < digitos.length; i++) {
acumulado += digitos[9 - i] * (2 + (i % 6));
}
var verif = 11 - (acumulado % 11);
if (verif == 11) {
verif = 0;
}
return digito == verif;
}
}}]).filter('cuit', function () {
/*
Format cuit as: xx-xxxxxxxx-x
or as close as possible if cuit length is not 10
*/
return function (number) {
/*
#param {Number | String} number - Number that will be formatted as cuit number
Returns formatted number: ##-########-#
if number.length < 2: ##
if number.length < 10: ##-########
if number.length === 11: ##-########-#
*/
if (!number) {
return '';
}
number = String(number);
// Will return formattedNumber.
// If phonenumber isn't longer than an area code, just show number
var formattedNumber = number;
//Type 20, 23, 24 y 27 Personas FĂ­sicas or 30, 33 y 34 Empresas
var type = number.substring(0, 2);
var main = number.substring(2, 10);
var verifyNumber = number.substring(10, 11);
if (main) {
formattedNumber = (type + '-' + main);
}
if (verifyNumber) {
formattedNumber += ('-' + verifyNumber);
}
return formattedNumber;
};});
This is the html:
<cuit-directive placeholder="'CUIT'" ng-model='vm.merchant.idNumber' required></cuit-directive>
I am invoking it within a form of course.
I am getting the data to my controller through a rest service, so I am doing something like:
function EditMerchantCtrl($state, $ionicHistory, merchantsService, $ionicPopup, $timeout, $ionicLoading) {
var vm = this;
function init(){
merchantsService.get().then(
function(response){
vm.merchant = response.data;
});
}}
I don't know why I can't get that field populated after receiving the response from the service. Any help would be much appreciated.
You should implement the $render function of the ngModelController, try something like this:
ngModel.$render = function() {
scope.inputValue = ngModel.$viewValue;
}
Hope it helps.

Turning JSON object value into decimal number after calculation

I have pulled in some data for my app via an external JSON url which has resulted in the value I require, which is currently a string that is "0.00"
result.data.app_payamount = "0.00"
When I convert my strings into numbers and calculate a value I am only being returned a part number and not a full decimal value used for currency.
How can I edit this code so the payamount displays a full decimal number suitable for currency?
var deferred = $q.defer();
var results = response.data;
var urlStart = 'http://exmaple.com/api';
if (response.config.url.startsWith(urlStart)) {
angular.forEach(results, function(result, key) {
result.data.CardFee = 2.00;
result.data.app_bookingfee = result.data.CardFee;
result.data.app_payamount = +result.data.app_subtotal + +result.data.app_handling + -result.data.app_discount + +result.data.app_adjustment + +result.data.app_bookingfee;
});
In js, you can specify the number of digits like this:
n = n.toFixed(2);
Try to use Number.toFixed() here.
var deferred = $q.defer();
var results = response.data;
var urlStart = 'http://exmaple.com/api';
if (response.config.url.startsWith(urlStart)) {
angular.forEach(results, function(result, key) {
result.data.CardFee = 2.00;
result.data.app_bookingfee = result.data.CardFee;
result.data.app_payamount = +result.data.app_subtotal + +result.data.app_handling + -result.data.app_discount + +result.data.app_adjustment + +result.data.app_bookingfee;
result.data.app_payamount = result.data.app_payamount.toFixed(2);
});
Use number.toFixed(2):
var n = 2;
var nStringInteger = n.toFixed(0); // "2"
var nString1Decimal = n.toFixed(1); // "2.0"
var nString2Decimal = n.toFixed(2); // "2.00"
Use parseFloat and toFixed
<!DOCTYPE html>
<html>
<body>
<p>Click the button to parse different strings.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function myFunction() {
var a = parseFloat("10.3265");
var b = parseFloat("10.00");
var c = parseFloat("10.33");
var n = a + b + c;
document.getElementById("demo").innerHTML = n;
document.getElementById("demo2").innerHTML = n.toFixed(2);
}
</script>
</body>
</html>
Use following currency directive to apply decimal places.
app.directive('currency', function ($filter, $locale) {
return {
require: 'ngModel',
scope: {
min: '=min',
max: '=max',
ngRequired: '=ngRequired'
},
link: function (scope, element, attrs, ngModel) {
function clearValue(value) {
value = String(value);
var dSeparator = $locale.NUMBER_FORMATS.DECIMAL_SEP;
var clear = value.match(/[\+\-0-9\.]/g);
clear = clear ? clear.join("") : 0;
return clear;
}
ngModel.$parsers.push(function (viewValue) {
cVal = clearValue(viewValue);
return parseFloat(cVal);
});
element.on("blur", function () {
if (isNaN(ngModel.$modelValue)) {
ngModel.$modelValue = 0;
element.val($filter('currency')(clearValue(ngModel.$modelValue)));
}
else {
element.val($filter('currency')(ngModel.$modelValue));
}
});
ngModel.$formatters.unshift(function (value) {
return $filter('currency')(value);
});
scope.$watch(function () {
return ngModel.$modelValue
}, function (newValue, oldValue) {
runValidations(newValue)
})
function runValidations(cVal) {
if (!scope.ngRequired && isNaN(cVal)) {
return
}
if (scope.min) {
var min = parseFloat(scope.min)
ngModel.$setValidity('min', cVal >= min)
}
if (scope.max) {
var max = parseFloat(scope.max)
ngModel.$setValidity('max', cVal <= max)
}
}
}
}
});

Categories

Resources