I' trying to call a doThis() function from my html after it has been generated from a <script>.
Because it is a script that runs an external url, I need to add it using a variable in my .ts file. It executes with no problem and creates my html element. That html element is a payment form, when it is completed, it calls a function that is inside the and gives me the order information as parameter.
My problem here is I'm trying to call a function in my .ts file from that html function to use that order information but I can't find a way to reference that .ts function from inside my html.
.ts file
export class Component implements OnInit {
giftupHtml: string = `<script type="text/javascript">
(function (g, i, f, t, u, p, s) {
g[u] = g[u] || function() { (g[u].q = g[u].q || []).push(arguments) };
p = i.createElement(f);
p.async = 1;
p.src = t;
s = i.getElementsByTagName(f)[0];
s.parentNode.insertBefore(p, s);
})(window, document, 'script', 'https://cdn.giftup.app/dist/gift-up.js', 'giftup');
// Track conversions:
giftup("conversion", function (payload) {
doThis();
});
</script>
`;
constructor( ) { }
doThis() {
console.log("This isn't called.");
}
Basically the giftupHtml is used as [innerHTML] inside a .
It renders fine and I know the html function is called since I can console.log(payload) but I can't reference my .ts file or function.
Anything you call outside the Angular zone will need to be wrapped in a call from ngZone. And make sure you use arrow functions so that the references to this stay as the component.
constructor(ngZone: NgZone) {
window['doThis'] = () => {
ngZone.run(() => {
// Now you have full access to the component here
});
};
}
ngOnDestroy() {
delete window['doThis'];
}
actually thats normal you are trying to access angular function from script window you cant do that normally but there is some workarounds
https://www.c-sharpcorner.com/blogs/call-angular-2-function-from-javascript
but i am really interested in the reason you are doing this for?
Related
I want to use this global variable in my Apps Script Addon:
var sheet_properties = PropertiesService.getDocumentProperties();
I've place it with other string global variables (out of functions in code.gs). It works well if I save and open the addon sidebar in my test implementation document, but if I refresh the document the Addon Menu disappears and I can't access the sidebar (only help tab is showing). The only way to bring back the menu is deleting the variable or putting inside a function, but I don't want to call getDocumentProperties in every function that use sheet_properties.
How could I proceed?
Thanks!
Try the IIFE pattern:
function someFunctionThatUsesProperties() {
sheet_properties.setProperty('test', 'test value');
console.log(`sheet props: ${JSON.stringify(sheet_properties)}`);
}
// ... at the end of the script file:
let sheet_properties;
function setGlobals_() {
sheet_properties = PropertiesService.getDocumentProperties();
}
(function () { setGlobals_() })();
Another alternative is to use a global props object, and always access it through a getter function, like this:
function anotherFunctionThatUsesProperties() {
const props = getProps_();
pros.sheet.setProperty('test', 'test value');
console.log(`sheet props: ${JSON.stringify(props.sheet)}, user props: ${JSON.stringify(props.user)}`);
}
// ... at the end of the script file:
const props = {};
function getProps_() {
if (Object.keys(props).length) {
return props;
}
props.sheet = PropertiesService.getDocumentProperties();
props.user = PropertiesService.getUserProperties();
return props;
}
File 1 - Monitor.js
var MONITOR = (function () {
// File Content
return {
doThing: function() {
doThing();
}
};
})();
File 2 - Test.js
var monitor = require('../public/js/monitor.js');
I want to access doThing() in File 2. I have tried various syntax and no luck so far.
From the frontend HTML I can simply include Monitor.js in a script tag, and call MONITOR.doThing(); without trouble but in Test.js this is proving difficult.
Any advice on how?
You have to export MONITOR so that someone else can access it with require().
Add this:
module.exports = MONITOR;
at the bottom of Monitor.js.
And, if you want the monitor.doThing() method to return some value, then you have to add a return statement to the function as in:
var MONITOR = (function () {
// File Content
return {
doThing: function() {
return "hello";
}
};
})();
To my html file i add 2 js files
<head>
<script type="text/javascript" src="js_001.js"> </script>
<script type="text/javascript" src="js_002.js"></script>
</head>
both those js files contain method call 'func1'
How i call func1 from js_002 ?
If there is method func1 => js_001
and method func2 => js_002
When i call the func2 from my html code - i get an error about that func2 does not exist on js_001 ... why is that and how to fix it ?
Functions defined with the same name in the global scope will overwite themselves. Last definition will overwite the previous one.
So you could populate your functions inside other scopes, for example, objects:
// In js_001.js
var js_001 = {
foo : function() {
}
};
// Inside js_002.js
var js_002 = {
foo : function() {
}
};
Then you can invoke both functions by: js_001.foo(); and js_002.foo();.
Hope it helps.
As others said you can't. That is why for example using modules is a good idea when you have larger applications.
You could write your scripts in your functions in the js files inside a module that includes all functions related to some functionality like this
File js_001.js
var js_001 = (function () {
return {
foo : function () {
// code
}
};
})();
File js_002.js
var js_002 = (function () {
return {
foo : function () {
// code
}
};
})();
And call your functions like this:
onclick="js_001.foo()"
onclick="js_002.foo()"
This question has already got some response here. But this doesn't seem to be working for me.
I am trying to create a tree structure using jQuery. The problem is I can not use a declared angular 4 variable inside a jQuery function. Here's the code.
employees = ["Mr. John", "Mr. Steve"];
ngOnInit() {
(function($) => {
function OrgChart($container, opts){
console.log(this.employees);
}
});
}
I see an error in console stating, "Function declarations are not allowed inside blocks in strict mode when targeting ES3 or ES5"
1st (the employees of undefined problem)
To bind the "this" of the component, use the arrow notation for functions :
($) => { console.log(this.employees)}
instead of function($) { ... }
2nd (the "function declarations are not allowed inside blocks")
You could declare your other inner function in another place in your Angular component, and then refer to it :
ngOnInit() {
// this declaration is nonsense to me, this will declare a function that is never called and exists only here, but anyway...
($) => {
// you can call OrgChart here :
this.OrgChart()
}
}
OrgChart($container, opts) {
console.log(this.employees);
}
You need store angular component reference in another variable before start jquery block.
export class PlanGruposComponent implements OnInit {
group = 'Meu grupo';
OnInit() {
//reference of currect component object
let temporaryThis = this;
$(document).ready(function () {
console.log("Print : " + temporaryThis.group);
});
}
}
I need to write & manage a lot of JavaScript code for current project.
I separate them into multiple .js files mainly based on module.
So, now i have for example:
Map.js // deal with google map issue
Common.js // common functions that will share by all modules
User.js // user module js code
Geofence.js // geofence module js code
etc.....
For example, inside my User.js file
what if i want to declare a function that only used inside the User.js file, not accessible by outside. what can i do?
var User = {};
User.registerModule = function () {
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
function getAllUsers(){ // how to hide this function
// get
return users;
}
So, in my home page, i only need to coordinate with multiple .js files. Access what allows to access.
$(document).ready(function (data) {
GoogleMap.initialiseGoogleMap();
Common.refreshRightScrollbar();
User.registerModule();
// ...
});
It is my first time to write js and not enough time to study a whole book. So, please, in your opinion, is this structure ok with many js code? and how to hide functions that i dont want outside to access?
to hide that function you have different possibilities
just enclose your code in an immediate self-executed anonymous function
var User = {}; // this should not be enclosed too
(function() {
User.registerModule = function () {
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
function getAllUsers(){ // how to hide this function
// get
return users;
}
})();
enclose that function inside User.registerModule function
User.registerModule = function () {
function getAllUsers() { ... }
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
Place this function inside the scope:
User.registerModule = function () {
function getAllUsers(){ // how to hide this function
// get
return users;
}
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers(); // returns users
// ...
});
}
And it will be private.
Now if you try to call this function outside it will be undefined:
getAllUsers(); // undefined.