Angularjs expression is not working for ng-bind and {{ }} - javascript

Angularjs addition is not working fro ng-bind and {{ }} but multiplication is working why?
I have the following code shown below
single_style.thread = 3;
single_style.stiching = 5;
and:
1) <td>{{single_style.thread + single_style.stiching}} </td>
2) <td>{{single_style.thread * single_style.stiching}}</td>
1) First i getting answer as 35
2) second i getting answer as 15
Even i use ng-bind its also not working why?

Update:
The problem was as suggested, you were trying to add strings which resulted in concatenation, After further reading and this great SO post shown below.
SO Answer
which says
Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.
Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.
So we can't use parseInt in angular brackets, we can either move the calculation inside a javascript function and call it from angular brackets. My Solution is, since (*) multiplication operator is doing type conversion, just multiply the variable by 1 so that you will get the same number and also convert the datatype to number. Then the calculation will be done as expected. Please let me know if this fixes your issue. The html will be as so.
<td>{{single_style.thread*1 + single_style.stiching*1}} </td>
Plunkr Demo
I think in your scenario the variables are strings. The + works as two ways, as an addition operator for numbers and as a concatenation operator for strings, so in your question, the first scenario, the operator is working as a concatenator and appending 3 and 5 as 35, for your second case, I think multiply operator (*) is doing type conversion before performing operation thus the correct calculation takes place (15), whereas in the first case type conversion is not taking place!
<td>{{parseInt(single_style.thread) + parseInt(single_style.stiching)}} </td>
<td>{{parseInt(single_style.thread) * parseInt(single_style.stiching)}}</td>

I think we miss something in your example.
+ operator concatenates strings '3' and '5' when * converts to int and makes multiplication. The same thing will woek for - and /
[EDIT]
Modify your data before you render it:
$scope.all_value = [];
angular.forEach(data, function(item){
item.thread = parseFloat(item.thread);
item.measure = parseFloat(item.measure);
item.bulk_qty = parseFloat(item.bulk_qty);
item.price = parseFloat(item.price);
item.pack_charge = parseFloat(item.pack_charge);
item.label = parseFloat(item.label);
item.elastic = parseFloat(item.elastic);
item.button = parseFloat(item.button);
item.markt_price = parseFloat(item.markt_price);
item.stiching = parseFloat(item.stiching);
$scope.all_value.push(item);
})
working example Demo
working example
$scope.single_style ={
thread: 3,
stiching: 5
};
and:
<p>{{single_style.thread + single_style.stiching}} </p>
<p>{{single_style.thread * single_style.stiching}}</p>
Output
8
15
Suppose your case when value is defined as string:
$scope.single_style ={
thread: '3',
stiching: '5'
};
and:
<p>{{single_style.thread + single_style.stiching}} </p>
<p>{{single_style.thread * single_style.stiching}}</p>
Output
35
15
Solution
The better way is to convert string to int on controller level, a.e.:
$scope.single_style ={
thread: parseInt('3'),
stiching: parseInt('5')
};
Demo

Related

Convert JS interpolation string to function call

I'm writing some code that rips string literals out of Typescript/JavaScript source as the first stage of a localisation toolchain I have planned.
The fly in the ointment is string interpolation.
I was on the verge of writing a function to transform an interpolation string into a function call that rips the expressions and then replaces the interpolation string with a function call that takes the expressions as parameters.
const a = 5;
const b = 7;
const foo = `first value is ${a + b}, second value is ${a * b}`;
becomes
import { interpolate } from "./my-support-code";
...
const a = 5;
const b = 7;
const foo = interpolate("first value is ${0}, second value is ${1}", [a + b, a * b]);
with the interpolate function working through the array values and replacing strings generated from the ordinal position
function interpolate(template: string, expressions: Array<any>): string {
for (let i = 0; i < expressions.length; i++) {
template = template.replace("${" + i + "}", expressions[i].toString());
}
return template;
}
This will probably work (not yet tried) but it occurred to me that this is probably a thoroughly invented wheel. The question is basically is there a well-established package that does a comprehensive job of this?
I know the above doesn't localise anything. The point is to be rid of interpolation strings so the substitution mechanism can assume that all strings are simple literals. The base language string taken from the above would be "first value is ${0}, second value is ${1}" and translators would be expected to place the tokens appropriately in whatever string they produce.
If you're going to tackle this on a non-trivial sized code base, the best you can really do is:
Write a regular expression to identify common types of localization targets and identify them, probably by file + line number.
Add comments to your code in these locations using a keyword that's easy to git grep for, or even something that can be added to your editor's syntax highlighting rules. Personally I use things like // LOCALIZE.
If you're feeling ambitious, you could implement a rewriter that attempts to convert from template form to your localization's template requirements. Each conversion can be individually inspected, altered as required, and introduced. Hopefully you have test coverage to verify your code still works after this.

Angular JS number filter

I had the following expression in Angular:
<br/><i>{{getFieldValue(teamMember.reportingData.fields, fieldname, 'meanValue' | number:2)}}</i>
where getFieldValue is a function on my controller. This was working as expected, and truncating the numeric result to 2 decimal places.
However, sometimes getFieldValue returns a string result. When that happens, it is not displayed at all. This is probably because truncating a string to 2 decimal places does not make sense.
To get round this, I tried to move the filter inside getFieldValue and only apply it to numeric results. To do this, I need a way of specifying a filter in Javascript, not as an expression in HTML. According to the docs this is possible, but the explanation is hard to follow.
Here is my attempt:
HTML:
<br/><i>{{getFieldValue(teamMember.reportingData.fields, fieldname, 'meanValue')}}</i>
part of getFieldValue :
if (field.numeric) {
fieldValue = $filter('number')([], field[aggregate], 2);
} else {
fieldValue = field[aggregate];
}
This does not work, I get what seems to be an empty string back. How to I do this properly?
Use like this
fieldValue = $filter('number')(field[aggregate], 2);
See Documentation of number filter.
var isnum = angular.isNumber(field[aggregate]);
if(isnum){
fieldValue = $filter('number')(field[aggregate], 2)
}else{
fieldValue = field[aggregate];
}
number filter in angularjs

JavaScript indexOf() Method giving -1 when decimal value is present in array

I'm having some trouble with the JavaScript indexOf() Method. I have an array...
pointLatArray = new Array();
When I try to get the index of a variable that I know is present in the array it returns -1, which I know normally indicates to the value not being found. When my code is as follows..
setlat = 52.6688391881732;
pointArrayIndex = pointLatArray.indexOf(setlat);
console.log(setlat + " " + pointLatArray[8] + " " + pointArrayIndex);
I get the following logged to console.....
04-16 12:35:31.370: D/CordovaLog(7048): 52.6688391881732 52.6688391881732 -1
However when I change the code by replacing setlat with pointLatArray[8] in the following line....
pointArrayIndex = pointLatArray.indexOf(pointLatArray[8]);
the following gets logged to console where it displays the correct index of 8 instead of -1 as expected.......
04-16 12:46:17.230: D/CordovaLog(8497): 52.6688391881732 52.6688391881732 8
Is it because I'm using such a long decimal set as the variable setlat? If so, or for what ever reason if anyone could suggest a fix I would appreciate it very much.
Many thanks
Strict comparison for double numbers is not a good idea. Probably what you observe here is rounding error. Although the numbers seem to be the same to you they may differ by a small epsylon.
One option I see is to use custom indexOf function using epsylon comparison(i.e. allow numbers to differ by a small value. For instance 0.000000000001 or 1e-12).

Is there any advantage of of using comma over + to concatenate primitive types in Javascript?

I have seen commas to concatenate primitive data types in Javascript and was wondering whether there was any difference in using a comma over say the + operator as well as the .concat() function?
So an example the following statement gives me abc
var value1 = a, value2 = b, value3 = c;
document.write(value1,value2,value3);
Apples and oranges. Nothing is being concatenated in your example; you are simply specifying 3 arguments to the write() function.
document.write(exp1, exp2, exp3, ...) accepts multiple parameters, and when given multiple parameters it will iterate through them all as if you called write() on each one individually.
However, the comma does have a use when evaluating expressions where it is used to process multiple expressions and returns the last one. To see that in action you need to wrap your parameters in a set of parenthesis so that it forms a single parameter:
document.write("a","b","c") // abc
document.write( ("a", "b", "c") ) // c
alert("a","b","c") // a
alert( ("a","b","c") ) // c
alert( (x=2, ++x) ) // 3
Since string concatenation is one of the haviest operations on computing, using document.write with various parameters would perform better.
See this test (it sometimes hangs in IE, so use other browser please) http://jsperf.com/document-write-vs-concatenation
Explaination:
document.write("val1", "val2", "val3");
is equivalent to
document.write("val1");
document.write("val2");
document.write("val3");
Thus, being much faster, since it doesn't concatenates the strings.
In most browsers (IE <= 8, Gecko) string concatenation using the + operator has horrible performance.
In my company, for example, we have to compose a large HTML fragment piece by piece. In this case we have something like this:
var id = 123;
var html = [];
html.push('<div id="', id, '">hello</div>');
var result = html.join('');
In the case where you have LOTS of concatenations, this is MUCH better than the following:
var id = 123;
result = '<div id="' + id + '">hello</div>';
So to answer your question - it really depends on the situation. If you are concatenating many strings together you should never use the + operator due to poor performance. But it should be fine 99% of the time where the performance gain will be so little it is just painful to try anything else. But in cases where you actually have the option to comma separate (like in the case of array.push, or document.write) then you should definately take advantage of it.

Javascript Sum Values

I need to sum several values in javascript. I've tried by using following code
var a = 2;
var b = 5;
c = a+b;
But, instead of calculating the values of a and b, the output (c) only combine those two values. So the output given is :
c = 25
I believe you guys can help me easily about this. Thx before. Regard Andha.
Make sure the values are numbers, otherwise they will concat instead of suming.
a = parseInt(a, 10); // a is now int
Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you're not saying:
var a = '2'; // or something similar
Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.
Or as pointed out in the comments the Number function would probably suit your purposes.
The author has probably put "simplified" code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using "Number()" solved the problem:
var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value);
This works fine:
var a = 2;
var b = 5;
var c = a + b; // c is now 7
The code you show will not work the way you describe. It will result in 7.
However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.
This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt() [docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter (radix) to ensure the casting from string to number uses the base you expect. (The lack of info on radix in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt().)
Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN() [docs].
Use parseInt():
var a=2;
var b=5;
c=parseInt(a)+parseInt(b);
-Is important to apply Number() to every value. The ideal way is:
var sum = 0
sum = Number('93') + Number('7') //result 100
-instead of this way (careful with this)
var sum = 0
sum = Number('97' + '3') //result 937
-and careful with this (as variable is going to assign string type by default)
var sum = 0
sum = Number('97') + '3' //result "973"
You can simply convert string to a number by adding + before it. For somebody can be more readable.
Example:
const a = "2";
const b = "5";
const c = +a + +b
or const c = (+a) + (+b) may be more readable.
That will first convert the string to a Number.

Categories

Resources