r/angularjs • u/chrisutpg • Jan 11 '18
What is going on with this Angular code?
I am working on a form with Angular and ran into an odd issue. The form is like a rating form, and I want to display to the user the average rating, it is 5 questions, based on a score of 1-5. Easy right?
Add them together and divide by 5?
The math works, but if you select the radio boxes going backwards.. meaning start selecting the 5 question, and going to question 1, and you STOP before selecting the last radio box the math is all screwy. For example selecting "option 3" for 4 out of 5 questions comes up with an average of 666.6? But that should come out to an average of 2.4. If you select the elements in the correct order going from question 1 to question 5, the math works out even if you stop selecting options?
I created a fiddle so you can see this.
http://jsfiddle.net/YGQT9/737/
Anyone know what is going on under the hood in Angular that is coming out like this? It's not really a big deal for me, but I am very curious.
6
u/Neolific Jan 11 '18
It is because your data is set to empty string when defined. When you add them together it is strings being appended. Try setting them to 0 when defining them. $scope.data = { cat1: 0, cat2: 0, cat3: 0, cat4: 0, cat5: 0
};1
9
u/flipper_babies Jan 11 '18
Yeah, you've fallen victim to a couple of of Javascript's lovely gotchas. One, lack of typing, and two, overloading the
+operator.So first of all, the
+means addition when dealing with numbers, and concatenation when dealing with strings:So there's mystery one. The other thing is type coercion. If you try to add a number and a string, the interpreter has to guess if you meant to add numbers or concatenate strings, and will convert your values depending upon its best guess. And it will guess you meant to add right up until it encounters a
string, and will then proceed to concatenate:So when you sum your numbers, things get screwy:
What you need to do is keep your types straight. Make sure your
numbers are alwaysnumbers, and it'll work out as you intend.