I have the external js file which has more functions.
I need to call these functions from angular controller.
For example: external.js
...
...
function fun() {
...
...
}
...
...
Controller: acccountController.js
myApp.controller('AddAccountController',function ($scope,AddAccountLoginServices,$location,localStorageService,$compile,toaster){
....
....
$scope.getLoginForm = function(siteId,name) {
...
...
fun(); // This function from external.js file
});
...
...
});
I have imported external.js before the acccountController.js. But it doesnt calling that function. And also i have not get any console error for this.
How to achieve this... Thanks in advance.
EDIT: gave wrong answer, my bad. the following example works.
your external file should like this:
var doSomething = (function () {
"use strict";
return {
test: (function () {
return 'test';
}()),
test2: (function () {
return console.log('test 2');
})
};
}());
and in your controller you call your scripts function:
console.log(doSomething.test);
or
doSomething.test2();
i learned something too, thanks ;)
As mentioned by #nilsK, you define a self invoking function. And then reference to it via window object. For example -
(function functionName(){
Do Something Here...
})();
And then,
window.functionName();
And if your are using AngularJS,
$window.functionName();
I have similar situation and I did not have to make it self invoking function. Including the external js file into the html and it worked fine.
Where is you call $scope.getLoginForm()?. I think you never call it. So fun() is not called, so you not see any thing. You need call $scope.getLoginForm(). Two way to call
In HTML <button ng-click="getLoginForm()"></button>
Or in Javascript $scope.getLoginForm()
Good luck !
You need to create a global instance of the function.
Add a line:
var abc= new funcName();
at the end of the File and you can use this line (var abc= new funcName();) in your controller to invoke any methods from this file by using abc.methodName.
Related
I know that $ is an alias to jQuery. Below code is passing an anonymous function to the $ function which can take a callback function.
$(document).ready(function() {
// ...
});
Perfect. It is simple and clear. But in one of the website I see below two files but could not understand what is it doing.
File 1
(function($, window, document, ns) {
"use strict";
...
...
})
($, window, document, Granite.author);
File 2
(function($,document) {
"use strict";
...
...
})(Granite.$, document);
Can anyone help me to understand what we are passing $, window, document, ns etc?
This is not necessarily a jQuery concept. It is creating a function and calling it immediatly.
Something like this:
(function (argument) {
console.log(argument)
})("This is being passed to the function")
Another way to do it using arrow functions would be
((argument) => { console.log(argument) })("This is being passed to the arrow function")
If you want a function that calling itself, you can define it between
(function hello(){
console.log("hello")
})()
This will automatically call the function and log the "hello".
I got this JQuery code:
file: code.js
jQuery(function(){
function renderSVG(){
//Something
};
});
File: index.html
<script>
function mostrarOdonto() {
renderSVG();
};
</script>
But i got a problem here:
http://i.gyazo.com/9550a64fc16c7570107706fb2162d84f.png in renderSVG() inside mostrarOdonto()
"Uncaught ReferenceError: renderSvg is not defined"
I tried $renderSVG(); but doesnot work. Anyone can help me?
Thanks so much!
PD: Sorry bad english
That is caused by javascript closures. It is local within the jQuery call and not accessible outside. You can read more about it here: MDN Documentation
You can declare objects outside of the jQuery function call to have it available globally. i.e.:
function RenderSVG(){
//Do Stuff
}
jQuery(function(){
RenderSVG();
});
This ensures that it is accessible outside the jquery scope
or if you really need it within jQuery you can go the route of a jQuery Plugin a la: jQuery docs
Example:
(function( $ ) {
$.fn.renderSVG = function( options ) {
//Do Stuff with canvas since it would be referenced in this.
};
}( jQuery ));
Then you can call it like: $('#mycanvas').renderSVG({/*options*/});
Update 1:
You have to ensure when your code is called after loading jQuery and any plugins.
in your <head> tag
you should put <script src=".../jquery.min.js"> or whatever your file for jquery is called
followed by any plugin scripts ...src="jquery.svg.js", then you put your code:
<script>
function RenderSVG(){
}
//And most important is that you call it after it is ready. In this example
//I use jQuery(window).load you can also use jQuery(document).ready
jQuery(window).load(function(){
RenderSVG();
});
</script>
if it still doesn't work you have to ensure the library for the svg methods aren't doing something weird. To be sure we would have to know the library you are using.
The function renderSVG() is a local function,since it is inside jQuery(function(){ }. It is valid only in that scope , So it is not accessible via other scopes. So try it like this.
<script>
jQuery(function(){
function mostrarOdonto() {
renderSVG();
};
};
</script>
You can Do it in this way JSFIDDLE LINK
HTML:
<input type="button" value="go" onclick=" mostrarOdonto();">
Scripts:
$.renderSVG = function() {
alert("I am calling form jquery");
};
$(document).ready(function() {
alert("function is ready to use now");
});
function mostrarOdonto() {
$.renderSVG();
};
This should work as per your requirement. The Jquery part can go into your Code.js file.
I think could help you it's simple and straight forward
$(document).ready(function() {
mostrarOdonto();
});
function renderSVG() {
alert("Testing purpose only");
};
function mostrarOdonto() {
renderSVG();
};
Below is my sample js in which everything is defined inside doDomReady function their are multiple function their.
`
YAHOO.namespace("YAHOO.User");
YAHOO.User = (function() {
Event.onDOMReady(UserData = function() {
.......
function save(){}
..........
});
})();`
From the above js file I want to call the save method from outside(from other js file) like this ->YAHOO.User.save(resultset) but I am not able to call it since it is not visible.
Anyone tell me how to call the functions in above case.
window.save == function(resultset){ ... }
This puts it in the global scope, so you could just call save() from another script. To namespace it under YAHOO.User, I suppose it would be:
window.YAHOO.User.save = function(resultset){ ... }
... then you can call YAHOO.User.save(resultset) from outside.
I have a file called function.js which has all my jQuery for my aplication which looks like this
$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
function update_gallery(product_id){
...
}
function update_prices(product_selector){
...
...
}
function insert_initial(){
...
}
$('.trigger').click(function(){
$('.stations').find(".drop-down").slideToggle();
return false;
});
...
...
On the top of the file i have my function call insert_initial(); which gets run on the initial load....and this works great..My problem is that i now need to include this js file on my php pages say 1.php and 2.php and 3.php and 1.php is the only one that needs the insert_initial(); ....so i was thinking of the best way to do this. I assumed taking out the function call out of the functions file and putting it into a separate file
<script src="/someting/js/functions.js" type="text/javascript"></script>
<script src="/someting/js/functions_insert.js" type="text/javascript"></script>
and in my functions_insert.js file i would have only
$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
});
but that didnt work either...any ideas on how to fix this
This checks to make sure that the location of the current page includes "1.php" before calling insert_initial():
if(window.location.href.indexOf('1.php') != -1)
insert_initial();
I would recommend having your definitions and executions separate in this instance. You don't need to define your functions inside of jQuery's DOM ready event. But it is also good to namespace them as mentioned. A common paradigm I follow is like so:
functions.js
(function($, window, undefined) {
function update_gallery(product_id){
...
}
function update_prices(product_selector){
...
...
}
function insert_initial(){
...
}
window.MyApp = {
update_gallery: update_gallery,
update_prices: update_prices,
insert_initial: insert_initial
};
})(jQuery, window);
1.php
<script src="functions.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
MyApp.insert_initial();
});
</script>
Now you can include your definitions as needed, and call them as necessary.
Try namespacing your functions and attaching them to a nice global object.
window.MyApp = {};
MyApp.insert_initial = function(){
};
Then you can access it from wherever you need, provided it's included earlier in the page.
Edit:
If this doesn't work, you've got an error elsewhere in your code - load order, perhaps? Either method you've described to invoke the function is fine, just make sure it's defined when you invoke it.
Your functions defined in functions.js are only visible in the scope of that document ready function. A simple case where it doesn't work:
(function() {
function square(x) {
return x*x;
}
})();
alert(square(2)); //Fails, since square is not in scope
The easiest way to fix this is to declare your functions in the global namespace:
function square(x) {
return x*x;
};
alert(square(2)); //4
Is it possible to load multiple scripts with same variables/functions in JS, without overriding the old value of the variable. For example to create an own scope/sandbox or object for each loaded script.
Files to load:
script1:
<script>
function init() {
do something...
}
</script>
script2:
<script>
function init() {
do something...
}
</script>
And after loading call script1.init() or script2.init(), is this possible?
You could wrap each section of code with a self invoking anonymous function, which will effectively namespace that section.
(function() {
function init() {
// do something...
}
})();
init(); // ReferenceError
However, if you can't change the code, the second init will overwrite the first definition.
However...
And after loading call script1.init() or script2.init(), is this possible?
...is confusing. Do you already have the init() as methods of an object? If so, they won't overwrite each other.
Unfortunately, no. There is a single global scope on a single page.
However, by using something like the module pattern, you can make a fake namespace:
For example:
var script1 = (function() {
var that = {};
that.init = function() {
do something...
};
more functions...
return that;
})();
And then call it by using script1.init();
You can find out more about the module pattern here.