Cordova + Angularjs + Device Ready - angularjs

I am developing a mobile application using Cordova and AngularJS. How do I restrict bootstrapping of AngluarJS before Cordova device ready. Basically I don't want to use any of AngularJS controllers before device ready.

Manually bootstrap your Angular app:
Remove your ng-app attribute from your HTML code, so Angular doesn't start itself.
Add something like this to you JavaScript code:
document.addEventListener("deviceready", function() {
// retrieve the DOM element that had the ng-app attribute
var domElement = document.getElementById(...) / document.querySelector(...);
angular.bootstrap(domElement, ["angularAppName"]);
}, false);
Angular documentation for bootstrapping apps.

I'm using the following solution, which allows AngularJS to be bootstrapped when running with Cordova as well as when running directly in a browser, which is where much of my development takes place. You have to remove the ng-app directive from your main index.html page since that's what the manual bootstrapping is replacing.
UPDATE: I've since switched to the following method, which I think is cleaner. It works for Ionic as well as vanilla Cordova/PhoneGap. It should be the last bit of JavaScript to run - perhaps inside a script tag before the /body tag.
angular.element(document).ready(function () {
if (window.cordova) {
console.log("Running in Cordova, will bootstrap AngularJS once 'deviceready' event fires.");
document.addEventListener('deviceready', function () {
console.log("Deviceready event has fired, bootstrapping AngularJS.");
angular.bootstrap(document.body, ['app']);
}, false);
} else {
console.log("Running in browser, bootstrapping AngularJS now.");
angular.bootstrap(document.body, ['app']);
}
});
Here's the older solution I used:
// This is a function that bootstraps AngularJS, which is called from later code
function bootstrapAngular() {
console.log("Bootstrapping AngularJS");
// This assumes your app is named "app" and is on the body tag: <body ng-app="app">
// Change the selector from "body" to whatever you need
var domElement = document.querySelector('body');
// Change the application name from "app" if needed
angular.bootstrap(domElement, ['app']);
}
// This is my preferred Cordova detection method, as it doesn't require updating.
if (document.URL.indexOf( 'http://' ) === -1
&& document.URL.indexOf( 'https://' ) === -1) {
console.log("URL: Running in Cordova/PhoneGap");
document.addEventListener("deviceready", bootstrapAngular, false);
} else {
console.log("URL: Running in browser");
bootstrapAngular();
}
If you run into problems with the http/https detection method, due to, perhaps, loading a Cordova app into the phone from the web, you could use the following method instead:
function bootstrapAngular() {
console.log("Bootstrapping AngularJS");
// This assumes your app is named "app" and is on the body tag: <body ng-app="app">
// Change the selector from "body" to whatever you need
var domElement = document.querySelector('body');
// Change the application name from "app" if needed
angular.bootstrap(domElement, ['app']);
}
// This method of user agent detection also works, though it means you might have to maintain this UA list
if (navigator.userAgent.match(/(iOS|iPhone|iPod|iPad|Android|BlackBerry)/)) {
console.log("UA: Running in Cordova/PhoneGap");
document.addEventListener("deviceready", bootstrapAngular, false);
} else {
console.log("UA: Running in browser");
bootstrapAngular();
}
Note that you still need the same bootstrapAngular function from the first example.
Why manually bootstrap AngularJS with Cordova/PhoneGap/Ionic?
Some people getting here might not know why you would want to do this in the first place. The issue is that you could have AngularJS code that relies on Cordova/PhoneGap/Ionic plugins, and those plugins won't be ready until after AngularJS has started because Cordova takes longer to get up and running on a device than the plain old Javascript code for AngularJS does.
So in those cases we have to wait until Cordova/PhoneGap/Ionic is ready before starting up (bootstrapping) AngularJS so that Angular will have everything it needs to run.
For example, say you are using the NG-Persist Angular module, which makes use of local storage for saving data on a browser, iOS Keychain plugin when running on iOS, and the cordova-plugin-file when running on Android. If your Angular app tries to load/save something right off the bat, NG-Persist's check on window.device.platform (from the device plugin) will fail because the mobile code hasn't completed startup yet, and you'll get nothing but a white page instead of your pretty app.

If you are using Ionic, this solution works for browsers and devices. Credit to romgar on this thread.
window.ionic.Platform.ready(function() {
angular.bootstrap(document, ['<your_main_app']);
});
Still need to remove ng-app from your DOM element.

This solution became more robust when I used:
angular.element(document).ready(function () {
var domElement = document.getElementById('appElement');
angular.bootstrap(domElement, ["angularAppName"]);
});
UPDATE
My suggestion was to put the above within the appropriate deviceready function, e.g.:
document.addEventListener("deviceready", function() {
angular.element(document).ready(function () {
var domElement = document.getElementById('appElement');
angular.bootstrap(domElement, ["angularAppName"]);
});
}, false);

On using the solution from TheHippo:
document.addEventListener("deviceready", function() {
// retrieve the DOM element that had the ng-app attribute
var domElement = document.getElementById(...) / document.querySelector(...);
angular.bootstrap(domElement, ["angularAppName"]);
}, false);
It doesn't work in the browser because "cordova.js" gets resolved by the Cordova or Phonegap building process and is not available in your localhost or emulated testing environment.
Thus the "deviceready" event is never fired. You can simply fire it manually in your browsers console.
var customDeviceReadyEvent = new Event('deviceready');
document.dispatchEvent(customDeviceReadyEvent);
Also make sure, that the bootstrap of angular gets triggered after setting all of you angular modules/controllers/factories/directives etc.

In most cases you probably don't need to block loading your angular app until after deviceready (mind that it can take several seconds for deviceready to fire if you have a lot of plugins).
Instead you can use something like this lib (https://github.com/arnesson/angular-cordova) which solves the deviceready issues for you by automatically buffering calls and then execute them after deviceready has been fired.

Related

InAppBrowser Events handling issue

I am working on mobile app using:
Ionic 2.1.4
Cordova 6.4.0
Angular 1.5.3
I've one view with external url using InAppBrowser plugin and I have a link in this website should redirect to certain view in my app
this issue is $location.url() not redirecting and not working at all, but when I tested the event I found it trigger normally.
here is my full code
angular.module('yogipass').controller('iframe',function ($location) {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log('here');
var ref=cordova.InAppBrowser.open('http://192.168.42.218/index.html', '_blank', 'location=no');
ref.addEventListener('loadstart', function(event) {
if (event.url.match("mobile/login")) {
console.log('worked!') // this logged normally
$location.url('/login');
ref.close();
}
});
}
])
You have to run digest cycle manually as you are changing location path from asynchronous event which is outside angular context.
Do wrap you code in $timeout function, which will fire up digest cycle. Apparently that will help to update location.
$timeout(function(){
$location.url('/login');
})

Golden Layout | Error: ng:btstrpd App Already Bootstrapped with this Element

I am using goldenlayout with angualrJS. I am facing below exception:
Error: ng:btstrpd App Already Bootstrapped with this Element
on execution of this line of code
myGoldenLayout.on('initialised', function () {
angular.bootstrap(angular.element('#layoutContainer')[0], ['app']);
});
The reason is, I have already ng-app in my HTML so how can I register golden layout when I already have ng-app?
https://github.com/codecapers/golden-layout-simple-angular-example/issues/1
Well, the official Golden Layout docs recommend using manual bootstrap, but if you want to keep using ng-app, then you have to make sure that your components (templates) are compiled by Angular (via $compile). Here's an example of how to do that:
angular.module('someApp') // your main module name here
.run(function ($compile, $rootScope) {
myLayout.registerComponent('template', function( container, state ){
var templateHtml = $('#' + state.templateId).html();
var compiledHtml = $compile(templateHtml)($rootScope);
container.getElement().html(compiledHtml);
});
myLayout.on( 'initialised', function() {
$rootScope.$digest(); // Golden Layout is done, let Angular know about it
});
});
// somewhere...
myLayout.init();
Basically, the main difference from the example in the repository you provided is that instead of just appending raw HTML, we $compile it with Angular, so now it knows to set up bindings and keep the html updated.
This should allow you to keep using ng-app instead of manual bootstrap.

How to bootstrap another angularjs app after the other?

Does anybody have an idea how to create an angularjs app with modules loginApp and mainApp, login will use login.html and mainApp will use index.html?
Below is the scenario I want to achieve.
Run loginApp
Once authenticated, run mainApp
I am currently doing the above scenario since I want my login page to load faster, so instead of using index.html which has lots of <script> included.
Angular app initialization manually.
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.greetMe = 'World';
}]);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
More information Bootstrap Angular App
You can manually bootstrap app. see here [more][1]
Manually Bootstrapping an AngularJS Application
Let's start by defining our application's main module:
var myApplication = angular.module("myApplication", []);
Now, instead of relying on the ng-app attribute, we can call the angular.bootstrap function manually. We need to hand it both the application root and the name of our main module. Here's how you call it as soon as the DOM has finished loading:
angular.element(document).ready(function() {
angular.bootstrap(document, ["myApplication"]);
});
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. -- http://docs.angularjs.org/api/ng.directive:ngApp
See also
https://groups.google.com/d/msg/angular/lhbrIG5aBX4/4hYnzq2eGZwJ
http://docs.angularjs.org/api/angular.bootstrap

How can I start fetching data from the server as quickly as possible?

How can I start fetching data from the server as quickly as possible with Angular?
Currently, most of my page is populated asynchronously via a directive "fooload" placed at the root element:
<html lang="en" ng-app="myapp" fooload ng-controller="MyAppCtrl">
<head>
/* bunch of CSS, and other resources */
</head>
Which loads data into the scope via an http GET request:
angular.module('myapp.directives').
directive('fooload', function ($http) {
return {
link: function (scope, elm, attrs) {
$http.get('/foo').success(function (data) {
scope.foo = data;
});
}
};
});
Looking at the network panel, this call is being made in the browser AFTER the requests for the resources referenced in head. How can I make the call to load /foo data as quickly as possible on page load (if possible, even before loading angular itself)?
This is not really related to Angular, obviously Angular cannot start loading files before Angular has loaded itself. But if the resource (eg /foo) is cacheable by the browser you could add it to a manifest file: http://www.html5rocks.com/en/tutorials/appcache/beginner/
I solved this by:
a) fetching the data even before angular loads and storing it in a global variable (I hate using a global variable, but I couldn't think of another way.)
b) manually bootstrapping angular upon load of this data (my app doesn't work at all without the data)
var $data;
var ajax_transport = new XMLHttpRequest();
// Callback for AJAX call
function responseProcess() {
if (ajax_transport.readyState !== 4) {
return;
}
if (ajax_transport.responseText) {
$data = JSON.parse(ajax_transport.responseText);
angular.bootstrap(document, ['myApp']);
});
}
}
// Sending request
ajax_transport.open("GET", "/mydata", true);
ajax_transport.onreadystatechange = responseProcess;
ajax_transport.send();
Note: it's important to remove the tag ng-app="myapp" in your template to avoid automatic bootstrapping.
c) Using the data in my angular app:
scope.setupSomething($data);
d) Also, to ensure that this data call begins before any other resource load, I started using a resource loader. I liked HeadJs (http://headjs.com/) the most, but the angular folks seem to like script.js (https://github.com/angular/angular-phonecat/blob/master/app/index-async.html)
Criticism or improvements welcome.
Start by creating a new service that gets the resource and then bootstraps the document for angular upon success callback from the server.
angular.element(document).ready(function() {
calllService(function () {
angular.bootstrap(document);
});
});
https://stackoverflow.com/a/12657669/1885896

AngularJS and google cloud endpoint: walk through needed

I'm new to AngularJS but I really like the way AngularJS works so I want to deployed it as client side for my Google cloud endpoint backend. Then I immediately get two problems:
1, Where to put the myCallback, so it's able to work into the ANgularJs controller?
<script src="https://apis.google.com/js/client.js?onload=myCallback"></script>
2, How I'm able to do the oauth2? and how the controller knows if the user authorized?
gapi.auth.authorize({client_id: myCLIENT_ID,
scope: mySCOPES,.....
Any help is appreciated.
For loading Google Javascript Library with AngularJs, the callback function passed to onLoad of Google Javascript Library is the function that bootstrap AngularJS, like this:
This goes to the final of html file:
<script src="https://apis.google.com/js/client.js?onload=startApp">
Then, in <head> section you bootstrap angular like this:
<script type='text/javascript'>
function startApp() {
var ROOT = 'http://<yourapi>.appspot.com/_ah/api';
gapi.client.load('myapifromgoogleendpoint', 'version1', function() {
angular.bootstrap(document, ["myModule"]);
}, ROOT);
}
</script>
As described by Kenji, you also need to remove ng-app directive from your html.
Regarding the callback - In order to access an Angular controller you need to use an injector (http://docs.angularjs.org/api/AUTO.$injector)
Simply create a global callback function, and then get reference to the controller from it like this:
window.callbackFunction() {
injector = angular.element(document.getElementById('YourController')).injector()
injector.invoke(function ($rootScope, $compile, $document) {
$rootScope.variable = "stuff you want to inject";
})
}
In this example I'm injecting the data to the rootScope, but this will also work for a specific controller scope (just inject $scope instead)
Can't help with the second question as I'm not familiar with gapi, though making auth2 calls from angularjs is quite straight forward.
Here you have details on how to use angularjs with google endpoints:
https://cloud.google.com/developers/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications?hl=es

Resources