Mathematical operation on angular template - javascript

Whenever I a try something like this in view template it is working as expected.
{{20*30}}
but whenever I try
{{somevalue1*somevalue2}}
Where somevalue1 and somevalue2 both are coming from component and somevalue2 is coming from api and it is inside an array, it is displaying NaN.
How to deal with that?
Is it because of the String value?
How to convert that in Number in template?

Is it because of the String value?
Yes, it is. You can't easily access the windows scope in template scope, so I would make a method:
calculateStuff(){
return Number(somevalue1) * Number(somevalue2);
}
And in template:
{{calculateStuff()}}
If the string doesn't start with characters representing number, it will still return NaN.

somevalue1 somevalue2 are probably strings. You'll need to share more code to get a real answer, though.
Add {{somevalue1}} and {{somevalue2}} to the template as well, just so you can be sure the template is receiving the values you expect.

Problem is the string value that is formatted according to some locale ( in your case it is US locale )
You can eighter:
convert the strings to values on data retrieving
create angular transform pipe
use a helper function/method in your template
if you are able, adjust data on the server side (it is a good practice sending raw data and formatting them when needed)
There are several ways how to handle the conversion. If this is the only format you receive that numbers. Simply replace the comma Number('1,234.42'.replace(',', '')) or use some of the libs that were created for this purpose like NumeralJS

Related

Ng Date Picker How to format to different output instead of ISO-8601

First, for people wondering, I'm referring to this DatePicker
https://danielykpan.github.io/date-time-picker/#locale-formats
While the DatePicker feels and looks great, I have an issue with the outputting values. There are numerous options to format the view-part of a date, but I haven't seen or found examples or explanations on how I can switch the outputted ISO-8601 (2018-08-29T00:00:00.000Z) standard in my form. I'm using the datepicker in a reactive form and I have several pages with a similar prerequisite. I need to parse this value into a different format. For example...
29-08-2018
My first attempt - which wasn't too smart to begin with - was using [(ngModel)]="dateField" to grab the value that is inputted and change it into a value that I wanted to. Needless to say, of course it was changed in the view as well and since I didn't refer to index of the form field it merely caused a blank field. Shortly after I realized that the approach was poor to begin with, but since I can't find configurations for this particular problem I'm pretty lost as to what I can do.
#ak.leimrey. Normally all the datepicker give you a value of one type (in your case a string format in ISO, other case, e.g. using ng-bootstrap, return an object with day,month and year). if you want to send in other format, in the submit you can map the values and convert the form.value.
submit(form)
{
if (form.valid)
{
let result={
...form.value, //all the values of the form, but change some one
searchParams:form.value.searchParams.map(x=>{
...x
value.map(v=>{
let items=v.split('-');
return items[2].substr(0,2)+"-"+items[1]+"-"+items[0];
})
})
}
console.log(result)
}
}
Yes in your case transform the object is some hard but see as using the spread operator and map you can transform the value
use moment js libaray . its a simple and rich library that can help u ;
u can get it via npm : npm i moment .
then u can convert formats like this :
moment("2018-08-29","YYYY-MM-DD").format("YYYY-DD-MM"); // outputs : 2018-29-08
or
moment("2018-08-29","YYYY-MM-DD").format("DD-MM-YYYY"); // outputs : 29-08-2018

Angular translate provider - Is there a way to replace general variables?

In my app, many of my translation string need to include the user name in them.
For example: Hello {{user_name}}!
(User name has to be part of the translation string since the position of the name in the string depends on the language))
The way to set attributes is {{"TRANSLATE_ID" | translate:{user_name:myUserName}}}
Since {{user_name}} appears in more than 100 translation strings, I don't want to send the user_name parameter so many times. I'd like to have a way to set this parameter only one.
I can't replace the {{user_name}} string in the config because the user_name is set asynchronously (fetched from the server) and isn't available when translateProvider sets the strings.
Thanks
AngularTranslate allows you to translate tags from the html itself or inside the controller through a promise. I believe the elegant way to do what you want is to create a method/function in your controller that handles the translation in the way you want and then call this method/function in your html passing the username as a parameter.
Address the username in your JSON translation files as "USERNAME" for instance, such as "Hello, USERNAME!", do the translation in a method created in your controller using AngularTranslate and then do a string replacement changing the word USERNAME for the method parameter (the real username) and use this string as the method's return value, which will be called in your html.
Hope this helps.

What is the right way to store JavaScript source code in a json object?

I want to edit JavaScript in a textarea and store it back into a JavaScript object. For example I have this object:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo") or a even more complex example does this break my object?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape. But it is marked as deprecated.
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object?
Should I use stringify ?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
This does not read like there is an automated escape build in.
If you need to send the data to a server, I'd say you should encodeURI your sourceCode, and then JSON.stringify the entire object. When retreiving data from the server, you should decodeURI the sourceCode

javascript array into object with same key names

I have an unusual problem to solve here. I have an array of Guids
[
"c01f8237-72c8-4fa6-9c53-1915750385aa",
"2c8a471b-c408-436c-81b1-3f3867d8ffb4",
"27a44d46-12bd-4784-ceed-57ada31b0e33"
]
This array has to be transformed into:
{
id: "c01f8237-72c8-4fa6-9c53-1915750385aa",
id: "2c8a471b-c408-436c-81b1-3f3867d8ffb4",
id: "27a44d46-12bd-4784-ceed-57ada31b0e33"
}
I know that shouldn't be done, but unfortunately cannot control the back end part. Any idea?
Thanks
The whole point of a dictionary key is that it uniquely maps to some value. Your desired output attempts to duplicate a key and therefore is neither possible nor does it make sense.
If you're passing this to a backend (as you suggest), then of course you can manually build a string to pass over the wire that duplicates keys in the payload, but you won't be able to actually do it in JavaScript first. You'll have to manually build the string.
Also note that you can call this format whatever you want, but you can't call it JSON and you can't use JSON libraries to build it (because it's not JSON). If your API expects a custom format, then you need to write code to build that custom format.
If all you want is a string just do something like
var str = '{' + idArray.map(function(id) {
return "id: "+id
}).join(',\n')+'}';
I have no idea what mime type you would put on that though since its not valid JSON.

regular expression to filter out part of key value in a json string

I have the following JSON string as part of a log line.
cells : {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"}
I want to filter out to the following format: {"Lac":"7824","Cid":"11983"}.
How can do this using regular expression ? in Javascript or Python ?
the keys are constant strings(Lac, CntryISO, ...), but the value strings are varying.
Why don't you just delete them in JavaScript?
var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"};
delete myJson.Lac;
delete myJson.cId;
To expand and explain #alex answer:
JSON is a nested multi dimensional structure. Simply filtering the "string-ifiyed form of a Javascript object" (aka JSON) will work in very simple cases, but will rapidly fail when the structure is no longer flat or it starts to get complex with escaped fields, etc.
At that point you will need proper parsing logic. This is nicely supplied by Javascript itself, to quote #alexes code:
var myJson = {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"};
delete myJson.Lac;
delete myJson.cId;
Or, if you want to use python, the json module will work just fine:
http://docs.python.org/library/json.html
Good luck! :)
Why would you want to use regex for this when you can just use a JSON parser/serializer? Try cjson in Python if you are concerned about speed, it is faster than 'json' module in the Python standard library.

Categories

Resources