I'm wish to use ngCordova to detect the network state of a device. However, as soon as I include cordova.js I get an error -
Uncaught ReferenceError: require is not defined (cordova.js:23)
I've installed and am successfully running Node.js and Cordova, and I've downloaded and installed ngCordova following the instructions here.
I have also installed the network-information plugin via the Cordova CLI -
cordova plugin add cordova-plugin-network-information
As per the documentation this is the code sample that I'm using (and to clarify, the error occurs as soon as I include cordova.js, so even without this code snippit I still get the error; this is show my end goal) -
var app = angular.module('myApp', ['ngCordova']);
app.controller('myCtrl', ['$rootScope', '$scope', '$cordovaNetwork', function($rootScope, $scope, $cordovaNetwork){
document.addEventListener("deviceready", function () {
var type = $cordovaNetwork.getNetwork()
var isOnline = $cordovaNetwork.isOnline()
var isOffline = $cordovaNetwork.isOffline()
// listen for Online event
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
var onlineState = networkState;
})
// listen for Offline event
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
var offlineState = networkState;
})
}, false);
}]);
In my index.html file I've made sure that I have declared the files are required in the order specified -
angular.min.js
ngCordova.min.js
cordova.js
How can I fix this error?
The answer here is that the Cordova CLI automatically includes
cordova.js
and any necessary dependancies when you build the application.The
cordova.js
file is placed in thewww
directory, so all you have to do is include that file -It seems illogical to reference a file that you are not inculding, but once you get your head around how the CLI works it makes sense.
The main problem for beginners is that it's quite poorly documented. In fact, Cordova as a whole seems to be poorly documented, not so much in terms of quantity but rather the relevance - so much is for old versions. It's a fantastic project though, and hopefully this is something that will be addressed in the near future.