how to execute some function in every time page reload in AngularJs? - javascript

I am trying to execute function every time page reloads.
I used this, But its not working properly.
$(window).load(function () {
$rootScope.pageClass = "page-fadein-down";
});
How to do this angularjs or jquery?
Any help ?

You can use angular app.run() block. Angualr JS Module docs
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
myApp.run(['$rootScope', function($rootScope) {
$rootScope.pageClass = "page-fadein-down";
}]);

Related

How do I setup an AngularJS app with onDeviceReady and initialize functions for Cordova?

I'm working on my first Cordova app to use AngularJS and I'm a bit lost as to how to coalesce the starting JS for a Cordova project.
I presently have the default index.js file that is included with Cordova that I've modified to include some events based on when the device goes on or offline. It creates an object (app) and adds functions for initialize, bindEvents, and onDeviceready.
Where should I define the AngularJS application? After the app.initialize() function call at the bottom of the document? Or can I ditch the original Cordova structure for the JS file entirely and do something else for the onDeviceReady?
Thank you!
Basically you can define angular anywhere, I recommend a separate file.
The thing you have to worry about is angular being loaded first before cordova.
Below is an example how to overcome this using a service.
.service('cordovaReady', function($q){
var cordovaDefer = $q.defer();
//Note: if you want browser support you'll need to detect
//what platform you're running because deviceready event won't be called
//unless cordova is running.
document.addEventListener("deviceready", cordovaDefer.resolve, false);
return function(){
return cordovaDefer.promise;
};
});
And using it every time you use a cordova plugin in your app like so:
//$cordovaFacebook is just an example
.controller('someCtrl', function(cordovaReady, $cordovaFacebook){
cordovaReady()
.then(function(){
//Plugins available here
$cordovaFacebook.api('/me').then(...);
});

How to calculate the page load time for angular JS application( single page application)

How to calculate the page load time programmatically for a angular JS (single page application)? I have used window.performance.timing for multi-page application, but it's not works properly for single page application. anybody help for track page load time on single page application? Please help.
I think you can achieve that by using Batarang + Chrome DevTools. It will help you track your app performance.
Update since the OP wanted to get page loading time programatically:
A possible solution might be the one provided to a similar question here.
You just have to get the current Date before loading any other scripts and get the date once the angular app hits the run phase. Then just subtract both dates and you get the loading time.
So, you will have:
<script type="text/javascript">
var timerStart = Date.now();
</script>
And then in your main angular module:
angular.module('app', []).
config(function() {
// some code
}).
run(function($window) {
console.log("Time until reaching run phase: ", Date.now() - $window.timerStart);
});
Didn't test but it should work.

Dynamically loaded AngularJS application

I'm looking to integrate an AngularJS web application into a number of websites. I'd like to be able to provide each website administrator with an HTML code, such as the following:
<div id='angular-integration-app'></div><script src="widget.js"></script>
With this HTML code inserted into the website, the website should load AngularJS and insert an AngularJS application as a child element of the element labeled with the ID of "angular-integration-app."
This Plunker has an implementation, however this implementation isn't working. It fails intermittently, with an error of:
Uncaught ReferenceError: angular is not defined application.js:1
Uncaught Error: [$injector:modulerr] angular.js:38
I've noticed that it usually works fine the first time it's loaded, but when the browser refresh button is pressed, it often fails. This is particularly true when it's not being hosted through Plunker.
Please advise on the best way to create a dynamic AngularJS application integration that works all the time.
This inconsistent behavior is because sometimes the page is cached and the code is executed synchonously, sometimes it does not.
To fix that, you need to wait for angular to be ready, then declare your module, and then bootstrap the document with your module. You cannot use ng-app in the HTML if the bootstrapping is executed "afterwards" (asynchronously, out of angular context). I have made the changes to show you how it should be:
var element = document.querySelector('#angular-integration-app');
angular.element(element).ready(function() {
var app = angular.module('myapp', []);
app.directive('customForm', function() {
return {
restrict: 'A',
template: 'hello world'
};
});
angular.bootstrap(element, ['myapp']);
});
http://plnkr.co/edit/7KbD1Okwx0MwhDIJXIGE?p=preview
Alternatively, if you don't want angular to mess up with your target html (and what happens if he is using another version of angularjs himself?), you could create an iFrame to isolate your angular, style, and code.
The code in this Plunker looks like it solves the problem. I'm now adding AngularJS as a child of the head element (the variable named "script"), and holding off on modifying the DIV or loading the AngularJS application until "script.onload." I incorporated some of the ideas from floribon's post into this Plunker as well.
script.onload = function() {
// code here
};

Where should I put deviceready on multipage PhoneGap App?

1) I have multiple pages PhoneGap applications. Each of them may call PhoneGap API.
Should I put deviceready listener on every pages, or is it sufficient to put on the first page only?
2) I use AngularJS routing with <ng-view> to enable single page application. The main page is index.html, all the other pages are just embedded on <ng-view>inside index.html. Each of those pages may call PhoneGap API. Is it sufficient to put deviceready listener on index.html only?
just add device ready in index.html as in angualrjs all other pages are going to be included in index.html by ng-view. deviceready should work fine this way.
Also bootstrap your angularjs after deviceready called as it can cause issues if you are going to use your app offline.
Hope this helps.
I made it works by putting device ready in index.html, and bootstrap angularjs in deviceready callback. However it is not optimized since it blocks the UI rendering until the connection to PhoneGap native process is established.
Better approach is described here. Basically he uses promise pattern, so that only Phonegap API call waits for the deviceready event. The UI rendering and angularjs bindings could be done even before deviceready is called. This way, the user experience would be better.
angular.module('fsCordova', [])
.service('CordovaService', ['$document', '$q',
function($document, $q) {
var d = $q.defer(),
resolved = false;
var self = this;
this.ready = d.promise;
document.addEventListener('deviceready', function() {
resolved = true;
d.resolve(window.cordova);
});
// Check to make sure we didn't miss the
// event (just in case)
setTimeout(function() {
if (!resolved) {
if (window.cordova) d.resolve(window.cordova);
}
}, 3000);
}]);
angular.module('myApp', ['fsCordova'])
.controller('MyController',
function($scope, CordovaService) {
CordovaService.ready.then(function() {
// Cordova is ready
});
});

Uncaught Error: [$injector:modulerr] Failed to instantiate module with LABJS

I keep getting this error when loading my Angular app. In Chrome a couple refreshes and my app will run but IE and FF is a no go.
The error links me to this error page but I don't really understand what it says.
I am loading my app using LabsJS including the controllers and service.
// spAppLoader.js
$LAB
.script("../js/app.js").wait()
.script("../js/controllers/userCtrl.js")
.script("../js/controllers/groupCtrl.js")
.script("../js/controllers/siteCtrl.js")
.script("../js/services/userServices.js")
.script("../js/services/groupServices.js")
.script("../js/services/siteServices.js")
Markup:
<div id="mdContainer" ng-app="spApp" ng-cloak>
...
</div>
<script type="text/javascript" src="../js/spAppLoader.js"></script>
I wanted to post more code but I don't know where to start and with angular everything is in multiple files. I uploaded it through github.
You should manually bootstrap your app because you use an asynchronous script loader:
$LAB
.script("../js/app.js").wait()
.script("../js/controllers/userCtrl.js")
.script("../js/controllers/groupCtrl.js")
.script("../js/controllers/siteCtrl.js")
.script("../js/services/userServices.js")
.script("../js/services/groupServices.js")
.script("../js/services/siteServices.js")
.wait(function(){
var root = document.getElementById('mdContainer')
angular.bootstrap(root ,['spApp']);
})
What is bootstrapping?
angular.bootstrap(root ,['spApp']); is the same as <div id="mdContainer" ng-app="spApp"> only the last one would automatically initialize your app when DOMContentLoaded event occurs.
When using a script loader, DOMContentLoaded event might happen before all scripts are loaded, so you must wait for all your module scripts and then bootstrap your application manually.
In your case, chrome probably cached your scripts so after few refreshes the DOMContentLoaded event happened after all scripts were loaded.
From the docs:
Automatic Initialization
Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is evaluated if at that time document.readyState is set to 'complete'. At this point Angular looks for the ng-app directive which designates your application root...
Manual Initialization
If you need to have more control over the initialization process, you can use a manual bootstrapping method instead. Examples of when you'd need to do this include using script loaders or the need to perform an operation before Angular compiles a page.
This error usually means angular can't find an object you are trying to inject into a controller or some other injectable function. After quickly looking through your code, my guess is that there is a problem with the way the files are being loaded, as you are referencing spApp from multiple files.
What I usually do is move separate files into their own modules, and then require other modules as needed. For example, instead of starting the userService like this:
spApp.factory('userService', function(){
put it into its own module
angular.module('spApp.services.user', [])
.factory('userService', function(){
Then whenever you need to use the userService in another module, add it as a requirement. Eg:
var spApp = angular.module('spApp', ['spApp.services.user']);

Categories

Resources