Angular JS number filter - javascript

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

Related

How to access the first two digits of a number

I want to access the first two digits of a number, and i have tried using substring, substr and slice but none of them work. It's throwing an error saying substring is not defined.
render() {
let trial123 = this.props.buildInfo["abc.version"];
var str = trial123.toString();
var strFirstThree = str.substring(0,3);
console.log(strFirstThree);
}
I have tried the above code
output of(above code)
trial123=19.0.0.1
I need only 19.0
How can i achieve this?
I would split it by dot and then take the first two elements:
const trial = "19.0.0.1"
console.log(trial.split(".").slice(0, 2).join("."))
// 19.0
You could just split and then join:
const [ first, second ] = trial123.split('.');
const result = [ first, second ].join('.');
I have added a code snippet of the work: (explanation comes after it, line by line).
function getFakePropValue(){
return Math.round(Math.random()) == 0 ? "19.0.0.1" : null;
}
let trial123 = getFakePropValue() || "";
//var str = trial123.toString();
// is the toString() really necessary? aren't you passing it along as a String already?
var strFirstThree = trial123.split('.');
//var strFirstThree = str.substring(0,3);
//I wouldn't use substring , what if the address 191.0.0.1 ?
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
Because you are using React, the props value was faked with the function getFakePropValue. The code inside is irrelevant, what I am doing is returning a String randomly, in case you have allowed in your React Component for the prop to be empty. This is to show how you an create minimal robust code to avoid having exceptions.
Moving on, the following is a safety net to make sure the variable trial123 always has a string value, even if it's "".
let trial123 = getFakePropValue() || "";
That means that if the function returns something like null , the boolean expression will execute the second apart, and return an empty string "" and that will be the value for trial123.
Moving on, the line where you convert to toString I have removed, I assume you are already getting the value in string format. Next.
var strFirstThree = trial123.split('.');
That creates an array where each position holds a part of the IP addrss. So 19.0.0.1 would become [19,0,0,1] that's thanks to the split by the delimiter . . Next.
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
This last piece of code uses the conditional if to make sure that my array has values before I try to splice it and join. The conditional is not to avoid an exception, since splice and join on empty arrays just returns an empty string. It's rather for you to be able to raise an error or something if needed. So if the array has values, I keep the first two positions with splice(0,2) and then join that array with a '.'. I recommend it more than the substr method you were going for because what if you get a number that's 191.0.0.1 then the substr would return the wrong string back, but with splice and join that would never happen.
Things to improve
I would strongly suggest using more human comprehensible variables (reflect their use in the code)
The right path for prop value checking is through Prop.Types, super easy to use, very helpful.
Happy coding!

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

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

Javascript: find asterisk in database field

I am checking a stream of data in Pentaho Data Integration and am using some Javascript. Certain fields may have one asterisk as the value. So I have:
if (Workgroup = "*") {
summary_level = "A";
} else {
summary_level = "W";
}
All values are getting set to "A", even fields where the value is not "*". I have tried:
Workgroup = /\\*/
Workgroup = /\*/
I know I have to escape it, just not sure how I have supposed to write it as a regular expression.
You are assigning, not comparing. What you want is if(Workgroup == "*"), the double = means is equal to.
This is the reason why a few programmers write it the other way, if("*" = Workgroup) would result in an obvious error, you cant overwrite a constant string.

JS Check Jquery inArray

I would like to use a onchange state on a select element to check if the value of the select is in an array.
I tried this :
function statutEmployeur(){
statliste = [];
statliste.push(1);
statliste.push(2);
statliste.push(5);
statid = jQuery("#statut").val();
if(jQuery.inArray(statid,statliste)>-1){
alert('inside array');
}else {
alert('outside array');
}
}
Each value that I tried are outside of the array.
Anybody can help me ?
Thanks
as pointed out by Stryner in the comments, try running your .val() through parseInt() to ensure you nave a numerical value (and not a string)
statid = jQuery("#statut").val();
to:
statid = parseInt(jQuery("#statut").val(), 10);
working fiddle: http://jsbin.com/maqesupuka/edit?html,js,console,output
the problem is you're searching in the array for a type of string (default type of inputs), but your array only contains numbers. You could either make your array into numbers, or do a type conversion like above to ensure you're working with the same type.

Wrong type of variable

I have a simple javascript/jquery function that looks like this:
$("#add_a, #add_b").on("change keyup paste", function () {
var add_a = $('#add_a').val(),
add_b = $('#add_b').val(),
add = add_a + add_b;
$("#add").text(add);
});
The problem is that it treats the variables add_a and add_b as strings even though i get the value from a input with type="number". I have made other similar functions and haven't had this problem before!
To making it clear, if I type in 3 in #add_a and 4 in #add_b the result is 34 and not 7.
Is there a way to make sure it get the values as numbers or change it after?
Thanks in advance!
As you say, values from <input>s are treated as strings. You need to parse them as a number, for that, you can use parseInt:
var add_a = parseInt($('#add_a').val(), 10),
add_b = parseInt($('#add_b').val(), 10)
If you're expecting non-integer input, you can use parseFloat instead.
You can take a look here and parse the value as an Integer. If an Integer is what you want...

Categories

Resources