Dynamically add javascript functions to an Angular project - javascript

Let's say that I have an angular service, this service calls a servlet asking for a library.js file containing my custom JavaScript functions.
Is there any way I can dynamically add these functions to my Angular application at run-time?
For example, in the library.js file I might have the following custom function:
helloWorld(){
alert("hello world");
}
It should work as follows:
1) I call the servlet using the standard Angular module HttpClient
2) The servlet sends back library.js, containing a list of functions, like helloWorld();
3) The angular web applications loads the library.js file (how?)
4) I can then call the helloWorld() function in my angular code.

Ok, we were able to solve the problem in the following way:
1) The servlet answers with the following message, the script tags are MANDATORY, it won't be recognized as valid js code otherwise.
String servletAnswer = "<script type=\"text/javascript\">
function helloWorld(){
alert("custom message!");
}
</script>"
2) The angular application subscribes and waits for the servlet to answer in the usual way. As soon as i get the response i do:
var script = response;
$('body').append(script); /* i append the script to body of the document,
now the function helloWorld is available to the application */
3) I call the function using eval:
eval("helloWorld()");
I hope it helps! Thanks everybody

Related

Angular 6 - call Angular function from external js file

Recently I'm rewriting a plan JS app with Angular 6.
The old stuff work like this:
file js inside a iframe that call "parent.update_track()" function defined into main.js file into iframe container.
that's not work in Angular when app run on production, the response is: TypeError: parent.update_track is not a function.
so how can I call this function "update_track()" declared into a ts file in a component from an external js file contained into iFrame?
You can use post message functionality.
So in your iframe you can just call the opener window (the parent) to post message, for more info you can use this reference
Then in the angular app (the parent) you can use the following listener:
#HostListener('window:message',['$event'])
onMessage(e) {
if (e.origin!="http://localhost:4200") {
return false;
}
alert('here i am');
}
}
Note: you should change the e.origin test to support both local env and production.

How do I add a personal script to an existing node.js library?

I have a local copy of the hls.js library and I need to include a personal script with custom functions in it.
How do I go about adding a new script to the library and how do I use the function written in the new script?
Let's say that I want to add a script called hello.js that contains a function that logs "Hello World".
When I call that function in my main.js I need it to execute.
Any ideas on how to do this?
Currently, I'm getting an error that the function is not defined.
I placed the hello.js script in the src folder of the library but this (as expected) doesn't seem to work.
It should be possible to add functions to the exported hls.js object.
Your custom-script.js:
var hls = require('hls.js')
hls.customFunc1 = function () {
}
hls.customFunc2 = function () {
}
on main.js:
require('custom-script')
// your code follows
Any other code would be able to use the custom functions by just require'ing hls.js.

pass data from javascript to asp.net core 2 razor page method

Is there any to pass some data from HTML property on changed event data to asp.net core razor pages?
I want to get an ID from dropdown list from HTML using JS and pass it to Razor Pages (asp.net core 2) and get the result from the custom method ?
Code I want to be look like below if possible :)
JS code
$('#Neighborhood_DistrictId').on('change', function () {
#Model.GetDistrictName($('#Neighborhood_DistrictId').val());
});
On the Razor page
public string GetDistrictName(Guid id)
{
return httpSystemApi.GetByIdAsync<District>("Districts", id).Result.Name;
}
GetDistrictName method is connecting to API and returning the value. I don't want to direct connect to API with JS if there is a way to do what I want
I am playing around with Razor Pages, and I have the same issue. Below is my work around. It seems like there should be some event handler will do the same thing, but I have not found another way yet. I tried treating it like the MVC controller, but I believe there is some form token that it is expecting so that did not work [name="__RequestVerificationToken"].
Basically what I am doing here, is tricking the page into thinking I clicked a button and then telling it which function to look at. Additionally, you have access to all your model fields so you do not need to pass them.
Here is the select list:
<div class="col-md-2"><select id="ddlPortalName" asp-for="selectedPortalName" asp-items="Model.portalNames" onchange="ConcatenateURL();"></select></div>
And then here is the JS function, notice I had to change the form action to tell it which page function to look at.
<script type="text/javascript">
function ConcatenateURL() {
document.forms[0].action = "VisibilityTest?handler=ConcatURL";
document.forms[0].submit();
}
</script>
And then finally here is the c# file method.
public void OnPostConcatURL()
$('#Neighborhood_DistrictId').on('change', function () {
#Model.GetDistrictName($('#Neighborhood_DistrictId').val());
});
#Model.GetDistrictName is a server side method not Usage directly inside script
$('#Neighborhood_DistrictId').on('change', function () {
var url="http://localhost/{controllername}/{methodname}/id=";
url=url+$('#Neighborhood_DistrictId').val()
$.get(url,function(data){
...some code
});
});
var url="http://localhost/{controllername}/{methodname}/id=";
In mvc 5 genrate url from server side and set the client side variable
var url='Url.Action("{action}","{controllername}","actionname")';
this is only way for call the controller using javascript or jquery not Directly use server side method in javascript.

Can I tell Javascript to call a method from another JS file?

In AppMenu.js,
AppMenu = function()
{
var scope = this;
}
Also noted:
Star.Bus.addEvent("AppMenu_StatSheet");
Star.Bus.on("AppMenu_StatSheet", scope.AppMenu_StatSheet, scope);
scope.registerApp("Exit Game", "AppMenu/images/exit_button.png", "AppMenu_exit", "");
Further down is a method
scope.AppMenu_StatSheet = function()
{
showStats();
}
I moved the location of the showStats() method to another js file, and I want the method to send its call there instead of where it originally was going. In Javascript, can I tell the program where to look to call showStats()?
EDIT Curiously, there is no AppMenu.html. I now believe that all of the html is dealt with by a main HTML file in the above folder.
If you include both Javascript files in your PHP/HTML page, the compiler automatically uses your showStats() function, even when it is called from file1.js and the actual function is located in file2.js.
As long as you include both files in your HTML page you'll be fine. Maybe load the file with showStats() before the other one.

How to get texts from Resx to be used in Javascript?

We are building large ASP.NET applications for the intranet use in multiple languages/cultures. We utilize the Globalization with RESX files and use GetResourceText on the server side to get the localized texts.
Lately we are doing more and more client side logic with JQuery.
How do I get the RESX texts to be used in Javascript?
e.g. texts used for validation, dynamic messages etc.
All our Javascripts are in .JS files, we do not want to mix HTML in the ASPX page and Javascript blocks.
Thanks for your help.
Unfortunately, in an external JS file the server side code is not being processed by the server. However I have seen a workaround where you can set your translated values in hidden fields on the page - this way your javascript will be able to read the values in.
For example:
<%-- This goes into your page --%>
<input type="hidden" id="translatedField" name="translatedField" value="<%=Resources.Resources.translatedText %>" />
and use this inside your javascript file:
// This is the js file
$(document).ready(function() {
alert($("#translatedField").attr("value"));
});
You will be able to separate the values and still see it in your external JS file.
There is also another workaround that creates a .aspx file that only outputs Javascript instead of HTML. Check out the link below:
Using server side method in an external JavaScript file
Always separate functionality from human readable strings.
If you're creating jQuery-plugins you should be able to pass an array of localized strings as parameter when you call your different jQuery functions. The array could be defined as inline javascript directly on the page calling the different jQuery plugins or you could load the from external resource in the format /scripts/localization/strings.js?ci=en-US and register a Generic ASP.Net Handler in web.config that would respond to scripts/localization/strings.js
The DatePicker control is a fine example of how to localize text for the jQuery datepick control - this js file is dynamically created from resource files (resx) and when included on a page it will make sure the calendar control will have danish text.
Create a HttpHandler (.ashx file), and return JSON with your text resource strings.
You may also "publish" it to global namespace, i.e.
Response.Write("window.Resources=");
Response.Write((new JavaScriptSerializer()).Serialize(strings));
set up HTML like:
<script src="Resx.ashx?lang=en-US" />
<button class="LogoutButtonResourceId OtherButtonClasses">(generic logout text)</button>
<a href="#"><span class="SomeLinkTextResourceId OtherClasses">
(generic link text)
</span></a>
and apply texts like this:
$(document).ready(function() {
for(var resId in Resources){
$("."+resId).html(Resources[resId]);
}
});
If you don't want to use ASP.NET to generate your main JavaScript, here are two other options:
Use ASP.NET to generate a script file that contains variable-to-string assignments, such as var mystring = 'my value';. Your main script would then reference the localized text with variables names rather than as embedded values. If that's still too "dirty" for you, you could encode the strings as JSON rather than as variable assignments, using an HttpHandler rather than straight .aspx.
Have your JavaScript code issue an Ajax call to retrieve an array or list of localized strings from the server. The server-side part of the call would retrieve the text from your resx files.
Have you considered using $.ajax in combination with ASP.NET WebMethods? It's hard to suggest a more concrete solution to this problem without understanding how your JavaScript/jQuery would consume/process the resources. I assume that they're organized into logical groups (or could be) where you could return several resource strings that belong on a single page.
Assuming that, you could write a very simple C# class -- or use a Dictionary<string, string> -- to return data from your ASP.NET WebMethod. The results would look something like:
[WebMethod]
public Dictionary<string, string> GetPageResources(string currentPage)
{
// ... Organizational stuff goes here.
}
I always separate out my AJAX calls into separate .js files/objects; that would look like:
function GetPageResources (page, callback)
$.ajax({ // Setup the AJAX call to your WebMethod
data: "{ 'currentPage':'" + page + "' }",
url: /Ajax/Resources.asmx/GetPageResources, // Or similar.
success: function (result) { // To be replaced with .done in jQuery 1.8
callback(result.d);
}
});
Then, in the .js executed on the page, you should be able to consume that data like:
// Whatever first executes when you load a page and its JS files
// -- I assume that you aren't using something like $(document).ready(function () {});
GetPageResources(document.location, SetPageResources);
function SetPageResources(resources) {
for (currentResource in resources) {
$("#" + currentResource.Key).html(currentResource.Value);
}
}
I know it's to late but want share my experience in this task)
I use AjaxMin. It can insert resx key values into js file on build event.
It's not common way but it keeps html without unneeded script blocks and can be done during minification process if you have it.
It works like this:
ajaxmin.exe test.js -RES:Strings resource.resx -o test.min.js
Also you need to do the same for ech locale if you have many.
Syntax to write resource keys in js (and also css) is written here:
Js localization
Css localization
How about injecting it as part of a javascript control initialization? what i do is as follows:
I have a self-contained javascript control - call it CRMControl, which has an init method called setupCRMControl, to which i pass a settings object. When i initialize it, i pass an object containing all the resources i need inside javascript as follows:
CRMControl.setupCRMControl({
numOfCRMs: 3,
maxNumOfItems: 10,
// then i pass a resources object with the strings i need inside
Resources: {
Cancel: '#Resources.Cancel',
Done: '#Resources.Done',
Title: '#Resources.Title'
}
});
Then, inside this javascript control:
var crmSettings = {};
this.setupCRMControl(settings) {
crmSettings = settings;
};
and whenever i want to show a resource, i say (for example, show an alert saying 'Done'):
alert(crmSettings.Resources.Done);
You can call it "R" to make it shorter or something, but this is my approach. Maybe this may not work if you have a whole bunch of strings, but for manageable cases, this may work.

Categories