window.onload does not work in AngularJS - window

This code in a simple HTML file works:
<script>
function load() {
alert("load event detected!");
}
window.onload = load;
</script>
However, if I put it into the index.html file of an AngularJS web app, it does not. Does anybody know why not?

Call your function with ng-init
var app = angular.module('app',[]);
app.controller('myController', function($scope){
$scope.load = function () {
alert("load event detected!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app'>
<div ng-controller='myController' ng-init='load()'></div>
</div>

I prefer putting this kind of code in the app.run() function of angular.
e.g.
angular
.module('testApp', ['someModule'])
.constant('aConstant', 'hi')
.config(function($rootProvider) {/*some routing here*/})
.run(['$window', function($window) {
$window.onload = function() {/*do your thing*/};
}]);
also check this nice post that depicts the order that some things happen in angular
AngularJS app.run() documentation?

the following should work:
jQuery(function(){ /** my window onload functions **/ })
since angular uses a subset of jquery anyways you also may include the real thing.
better yet:
Instead of using this, you may consider using the angular way of initialising things:
that would be: http://docs.angularjs.org/api/ng.directive:ngInit
< any ng-init="functionInController(something)"...
to make it invisible until init: http://docs.angularjs.org/api/ng.directive:ngCloak
< any ng-cloak .....
to initialise/customize whole parts: http://docs.angularjs.org/guide/directive
< any directive-name....

Try
angular.element($window).bind('load', function() {
});

Related

laravel passing a variable to js file from a controller

I have a js file located in assets folder (not View). can i pass a varible from a controller?
In view file:
The Js is called like this
<canvas id="chart1" class="chart-canvas"></canvas>
</div>
It is not possible (in my point of view) to put a variable to external JS file. You can use data-... attributes and get values from html elements.
For example you can pass your PHP variable as a json encoded string variable in your controller.
$data['chart_info'] = json_encode($chart_info);
return view('your_view', $data);
Then put it in data-info like this.
<canvas id="chart1" class="chart-canvas" data-info="{{ $chart_info }}"></canvas>
And finally in JS, you can get the variable and decode (parse) it as following.
let canvas = document.getElementById('chart1');
let info = JSON.parse(canvas.dataset.id);
console.log(info);
You can put that part of the Javascript in the view and send the variable to the same view. For example, add a section in view:
#section('footer')
<script type="text/javascript">
</script>
#endsection
Do not forget that you should add #yield('footer') to the end of your layout view.
I don't like to mix javascript and PHP/Blade, it might be hard to read the code in the future... You could use a different approach, loading the chart with a async ajax request.
You will have to create a end-point that returns the data you need for your chart:
Your router:
Route::get('/chart/get-data', [ ControllerName::class, 'getChartData' ]);
Your controller method:
public function getChartData() {
$chartData = [];
// Your logic goes here
return $chardData;
}
In your javascript (using jquery) file there will be something like that:
function loadChartData() {
$.ajax({
'url': '/chart/get-data',
'method': 'GET'
})
.done((data) => {
// Load your chart here!!!
})
.fail(() => {
console.log("Could not load chart data");
});
}
Hope I helped ;)

Jquery In rails won't load for masonry

How can i load the jquery with rails. I have try in the following
<script src="jquery-1.7.1.min.js"></script>
<script src="jquery.masonry.min.js"></script>
<script>
$(function () {
var $container = $('#container');
$container.imagesLoaded(function () {
$container.masonry({
itemSelector: '.item'
});
});
});
</script>
But i am getting an error. This is included in my html code. Not in the header. Now I come to realize when clicking on it i get the error route not set up. How can i load it the proper way.
See application.js.
By default, jquery is part of rails starting from rails 3. You dont need to include it separately.

jQuery(document).ready() won't work on AJAX loaded jQuery-UI widgets

I am loading some code with the jQuery.ajax() method. In this code I want to have some jQuery-UI Widgets (sliders and calenders) but they won't appear in IE.
Here some example code where you maybe can help me to understand where I am going wrong.
The Code which will load the jQuery-UI Widgets
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
}
});
});
</script>
The Code which is loaded and SHOULD initialize the jQuery-UI Widgets
<script>
jQuery(document).ready(function(){
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
});
</script>
<div class="datepicker-div">
<div class="slider-div">
You can see that it should be very simple. For FF it works fine but not for IE.
Maybe it has nothing to do with the document-ready statement?
Just call the initializers in the success event:
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
}
});
});
</script>
Of course, you should refactor that by having a function for initializations:
function Initialize(){
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
}
Then have your success call it, as well as the ready() ebent:
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
Initialize();
}
});
});
</script>
Update
I have read your question more carefully and now I fully understand it. Your ready() is in the loaded code. Then you should be using jQuery's load():
Script Execution
When calling .load() using a URL without a suffixed selector
expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is called with a selector expression appended to the URL,
however, the scripts are stripped out prior to the DOM being updated,
and thus are not executed. An example of both cases can be seen below:
Here, any JavaScript loaded into #a as a part of the document will
successfully execute.
$('#a').load('article.html');
Try removing the scripts prior to appending the html, then adding them back.
var outHTML = data.replace(/<script>/ig,"<div class='script'>").replace(/<\/script>/ig,"</div>");
outHTML = $(outHTML);
var script = outHTML.find("div.script").detach();
$(".somediv").html(outHTML);
var s = document.createElement("script");
s.textContent = script.text();
document.body.appendChild(s);
Edit:
.find("div.script") may need to be changed to .filter("div.script") based on what your ajax request is returning.
Ok, I didn't found out how i can solve the Problem, but i found a work around.
The work around is very simple. Because in every browser except for the IE the loading of the script via ajax works fine, we have to identify the IE and change the behaviour to not loading the script but redirect to the site I wanted to load. I am doing this all in Joomla 2.5, so there was a bit work to do but basically it was the following code wich solved the problem.
// preparing the url
// check for ie
if (jQuery.browser.msie) {
window.location(url);
} else {
// do the ajax
}

Using Jquery in Controller Page-ASP.NET MVC-3

Could any one give an example, how to use Jquery in Controller Page. MVC3 -ASP.NET(How To put various tags like )
I want to show a simple alert before rendering a view in Controller.
Thank you.
Hari Gillala
Normally scripts are part of the views. Controllers shouldn't be tied to javascript. So inside a view you use the <script> tag where you put javascript. So for example if you wanted to show an alert just before rendering a view you could put the following in the <head> section of this view:
<script type="text/javascript">
alert('simple alert');
</script>
As far as jQuery is concerned, it usually is used to manipulate the DOM so you would wrap all DOM manipulation functions in a document.ready (unless you include this script tag at the end, just before closing the <body>):
<script type="text/javascript">
$(function() {
// ... put your jQuery code here
});
</script>
If you are talking about rendering partial views with AJAX that's another matter. You could have a link on some page that is pointing to a controller action:
#Html.ActionLink("click me", "someAction", null, new { id = "mylink" })
and a div container somewhere on the page:
<div id="result"></div>
Now you could unobtrusively AJAXify this link and inject the resulting HTML into the div:
$(function() {
$('#mylink').click(function() {
$('#result').load(this.href, function() {
alert('AJAX request finished => displaying results in the div');
});
return false;
});
});

jQuery Ajax don't remember generated code?

I just started using Ajax with jQuery and PHP. I have a working code (below) which inserts some HTML code to a HTML container (div called nav sub).
Next time I try to run a similar code to the one below on my generated HTML, jQuery don't seem to find it. I guess it don't update it self about it when it's added.
$(".nav.top a").click(function(){
var a_class = $(this).parent().attr("class");
$(".nav.sub").html("loading...");
$(".nav.sub").load("<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",{button: a_class});
return false;
});
Let's say the generated code looks like this:
<div class="nav sub">
My new generated button, forgotten by jQuery?
</div>
And the new container looks like this:
<div class="settings"><?php # AJAX ?></div>
Is it some way to use jQuery and Ajax on HTML code generated with jQuery?
I figured it out. The solution is to use "live".
$('.nav.top a').live( 'click', function() {
var a_class = $(this).parent().attr("class");
$(".nav.sub").html("loading...");
$(".nav.sub").load("<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",{button: a_class});
return false;
});

Resources