Ionic: trouble using ngCordova to check online/offline status - angularjs

I'm using ngCordova "Network Information" plugin to get the online/offline status of the host device. I have followed this tutorial (which excellent, as are his other posts):
Josh Morony - Monitoring Online and Offline States in an Ionic Application
I have implemented the "ConnectivityMonitor" service as described in the article.
In one of my controllers/templates it works perfectly:
(function() {
'use strict';
angular
.module('myApp')
.controller('ResearchController', ResearchController);
ResearchController.$inject = ['$scope', '$stateParams', 'MyApi', 'ConnectivityMonitor'];
function ResearchController($scope, $stateParams, MyApi, ConnectivityMonitor) {
var vm = this;
vm.isOnline = ConnectivityMonitor.isOnline();
...
}
<ion-view title="RESEARCH" ng-controller="ResearchController as vm" >
<ion-content>
<div>
ONLINE: {{vm.isOnline}}
</div>
</ion-content>
</ion-view>
Result:
ONLINE: true
However, in another controller/template this does not work and I have been at this for hours and hours:
(function() {
'use strict';
angular
.module('MyApp')
.controller('HomeController', HomeController);
HomeController.$inject = ['$scope','ConnectivityMonitor'];
function HomeController($scope, ConnectivityMonitor) {
var vm = this;
vm.isOnline = ConnectivityMonitor.isOnline();
activate();
////////////////
function activate() {
}
}
})();
<ion-content class="background" ng-controller="HomeController as vm">
<p>ONLINE: {{vm.isOnline}}</p>
</ion-content>
Result:
ONLINE: {{vm.isOnline}}
Here ^^^ it seems that angular is not performing the databinding. I have all of my relevant controllers in index.html, as well as angularjs references.
Here is my implementation of the "ConnectivityMonitor" service:
(function() {
'use strict';
// http://www.joshmorony.com/monitoring-online-and-offline-states-in-an-ionic-application/
angular.module('MyApp').factory('ConnectivityMonitor', ['$rootScope', '$cordovaNetwork', connectivityMonitor]);
function connectivityMonitor($rootScope, $cordovaNetwork) {
return {
isOnline: function () {
if (ionic.Platform.isWebView()) {
return $cordovaNetwork.isOnline();
} else {
return navigator.onLine;
}
},
isOffline: function () {
if (ionic.Platform.isWebView()) {
return !$cordovaNetwork.isOnline();
} else {
return !navigator.onLine;
}
}
};
}
}
)();
Any idea why this would not be working? I'm new to AngularJS and Ionic so I'm thinking there is some nuance or convention that I'm overlooking. Thanks.
[ UPDATE 1 ]
I recreated this issue in an ionic starter app. There are two templates: Home.html and Workshere.html, with respective controllers. The online status is correctly displayed in the "Workshere" state, and is incorrect in the "Home" state. Also, adding the HomeController to Home.html (via ng-controller) seems to kill all interactivity on that page, can't even click the "Go to Workshere" link.
Home.html and home state is the default state for the MyApp. I'm starting to think that this is a timing issue an ConnectivityMonitor is not ready when the home state loads.
Code follows:
Home.html
<ion-view>
<ion-content ng-controller="HomeController">
<br/><br/><br/>
<p>HOME</p>
<p>ONLINE: {{vm}}</p>
<br/><br/>
<a ui-sref="workshere">Go to WorksHere</a>
</ion-content>
</ion-view>
home.controller.js
(function() {
'use strict';
angular
.module('myApp')
.controller('HomeController', HomeController);
HomeController.$inject = ['$scope','ConnectivityMonitor'];
function HomeController($scope, ConnectivityMonitor) {
$scope.vm = ConnectivityMonitor.isOnline();
activate();
////////////////
function activate() {
}
}
})();
Workshere.html
<ion-view ng-controller="WorkshereController as vm" >
<ion-content>
<br/><br/><br/>
<p>WORKS HERE</p>
<p>ONLINE: {{vm.isOnline}}</p>
<br/><br/>
<a ui-sref="home">Go to Home</a>
</ion-content>
</ion-view>
workshere.controller.js
(function() {
'use strict';
angular
.module('myApp')
.controller('WorkshereController', WorkshereController);
WorkshereController.$inject = ['$scope', 'ConnectivityMonitor'];
function WorkshereController($scope, ConnectivityMonitor) {
var vm = this;
vm.isOnline = ConnectivityMonitor.isOnline();
activate();
////////////////
function activate() {
}
}
})();
app.js
angular.module('myApp', ['ionic', 'ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home.html'
})
.state('workshere', {
url: 'workshere',
templateUrl: 'workshere.html'
});
$urlRouterProvider.otherwise('/');
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/connectivityMonitor.js"></script>
<script src="js/home.controller.js"></script>
<script src="js/workshere.controller.js"></script>
</head>
<body ng-app="myApp">
<ion-nav-view>
</ion-nav-view>
</body>
</html>
ConnectivityMonitor.js
(function() {
'use strict';
// http://www.joshmorony.com/monitoring-online-and-offline-states-in-an-ionic-application/
angular.module('myApp').factory('ConnectivityMonitor', ['$rootScope', '$cordovaNetwork', connectivityMonitor]);
function connectivityMonitor($rootScope, $cordovaNetwork) {
return {
isOnline: function () {
if (ionic.Platform.isWebView()) {
return $cordovaNetwork.isOnline();
} else {
return navigator.onLine;
}
},
isOffline: function () {
if (ionic.Platform.isWebView()) {
return !$cordovaNetwork.isOnline();
} else {
return !navigator.onLine;
}
},
startWatching: function(){
if(ionic.Platform.isWebView()){
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
console.log("went online");
});
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
console.log("went offline");
});
}
else {
window.addEventListener("online", function(e) {
console.log("went online");
}, false);
window.addEventListener("offline", function(e) {
console.log("went offline");
}, false);
}
}
};
}
}
)();
Please see comments at the "UPDATE 1" marker.

Why don't you try it this way:
function HomeController($scope, ConnectivityMonitor) {
$scope.vm = ConnectivityMonitor.isOnline();
}
and for view
<ion-content class="background">
<p>ONLINE: {{vm}}</p>
</ion-content>

Related

angular.js with vendor.min.js getting Uncaught Error: [$injector:modulerr]

I am trying to use require.js with Main.js and getting following error:
http://errors.angularjs.org/1.4.12/$injector/modulerr?p0=bleepMed&p1=Error%3
(http%3A%2F%2Flocalhost%3A8000%2Fjs%2Fvendor.min.js%3A25%3A274)
My Main.js
'use strict';
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
};
angular.module('bleepMed', [
' ui.router',
'angular-loading-bar',
'ngAnimate',
'ui.bootstrap',
'ui.bootstrap.datetimepicker',
'angular-ui-validator',
'toastr',
'angular-uuid',
'colorpicker.module',
'naif.base64',
'highcharts-ng',
'ui.gravatar',
'ds.clock',
'sun.scrollable',
'ngFileUpload',
'countTo',
'angularMoment',
'ngSanitize',
'textAngular',
'ui.grid',
'ui.grid.resizeColumns',
'ui.grid.pagination',
'ngDraggable',
'timer',
require('./common').name,
require('./config').name,
require('./modules').name,
require('./util').name
])
.config(['cfpLoadingBarProvider', '$urlRouterProvider', 'AppConfig', 'toastrConfig', '$locationProvider', function(cfpLoadingBarProvider, $urlRouterProvider, AppConfig, toastrConfig, $locationProvider) {
//for angular bar loading
cfpLoadingBarProvider.includeSpinner = false;
$urlRouterProvider.when('/', ['$state', 'loggedInUser', function($state, loggedInUser) {
if (!Object.keys(loggedInUser.getData()).length) {
$state.go('login');
} else {
$state.go('admin.home');
}
}]);
angular.extend(toastrConfig, AppConfig.toastr);
// $locationProvider.html5Mode(true).hashPrefix('*');
// $translateProvider
// .useStaticFilesLoader({
// prefix: '/translations/',
// suffix: '.json'
// })
// .preferredLanguage('en')
// .useMissingTranslationHandlerLog();
}])
// .constant('moment', require('moment-timezone'))
.run([
'$rootScope',
'$injector',
'loggedInUser',
'$state',
'toastr',
'$timeout',
'$window',
'AppConfig',
'API',
function($rootScope, $injector, loggedInUser, $state, toastr, $timeout, $window, AppConfig, API) {
console.log("in......");
$rootScope.googleChartLoaded = false;
$rootScope.picUrl = API.picUrl;
$rootScope.$on('$stateChangeStart', function(event, toState, fromState) {
if (Object.keys(loggedInUser.getData()).length && (toState.name.indexOf('login') > -1)) {
event.preventDefault();
}
if (!Object.keys(loggedInUser.getData()).length && (toState.name.indexOf('admin') > -1)) {
event.preventDefault();
$state.go('login');
}
});
$rootScope.$on('$stateChangeSuccess', function() {
$rootScope.loadingText = '';
$rootScope.pageLoading = false;
});
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
$rootScope.pageLoading = false;
});
$rootScope.$on('invalidToken', function() {
$state.go('login');
});
//for google chart//
google.charts.load('current', {
'packages': ['corechart', 'bar']
});
function googleChartLoadedCallback() {
$timeout(function() {
// console.log('here in timeout');
$rootScope.googleChartLoaded = true;
$rootScope.$broadcast('chartLoaded', {});
}, 0);
}
google.charts.setOnLoadCallback(googleChartLoadedCallback);
$rootScope.goBack = function() {
$window.history.back();
};
//mqtt starts
$rootScope.client = mqtt.connect(API.mqtt);
$rootScope.client.on('connect', function() {
console.log('connected');
});
$rootScope.client.on('subscribe', function() {
console.log('subscribe');
});
}
]);
My index.html
<!DOCTYPE html>
<html ng-app="bleepMed">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1,
maximum-scale=1">
<!-- <base href="/"> -->
<title>Bleep Med</title>
<!--Stylesheet-->
<link rel="stylesheet" type="text/css" href="./css/vendor.min.css">
<link rel="stylesheet" type="text/css" href="./css/app.min.css">
</head>
<body>
<div ui-view ng-class="moduleClass" class="full-height ui-view-class">
</div>
<!-- <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCV7dBG_5koAJ_HmwRDEc7l4jezGbpHyfs&libraries=places">
</script> -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCCE7DhZbQJ8-ki453Z2JdGzPJdMZ5o5JM&libraries=places"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="resources/js/mqtt.js"></script>
<script src="./js/vendor.min.js"></script>
<script src="./js/main.min.js"></script>
</body>
</html>
I got an error that said I need to add ngroute to my app but I still get this error. Can anyone point me to what i might be doing wrong?
My exact error is:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.1/$injector/modulerr?p0=bleepMed&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.2.1%2F%24injector%2Fmodulerr%3Fp0%3Dsun.scrollable%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.2.1%252F%2524injector%252Fnomod%253Fp0%253Dsun.scrollable%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.2.1%252Fangular.min.js%253A6%253A447%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.2.1%252Fangular.min.js%253A20%253A159%250A%2520%2520%2520%2520at%2520a%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.2.1%252Fangular.min.js%253A19%253A353)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.2.1%252Fangular.min.js%253A20%253A54%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.2.1%252Fangular.min.js%253A28%253A487%250A%2520%2520%2520%2520at%2520Array.forEach%2520(%253Canonymous%253E)%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.2.1%252Fangular.min.js%253A7%253A255)%250A%2520%2520%2520%2520at%2520e%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.2.1%252Fangular.min.js%253A28%253A427)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.2.1%252Fangular.min.js%253A28%253A504%250A%2520%2520%2520%2520at%2520Array.forEach%2520(%253Canonymous%253E)%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.1%2Fangular.min.js%3A6%3A447%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.1%2Fangular.min.js%3A29%3A279%0A%20%20%20%20at%20Array.forEach%20(%3Canonymous%3E)%0A%20%20%20%20at%20p%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.1%2Fangular.min.js%3A7%3A255)%0A%20%20%20%20at%20e%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.1%2Fangular.min.js%3A28%3A427)%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.1%2Fangular.min.js%3A28%3A504%0A%20%20%20%20at%20Array.forEach%20(%3Canonymous%3E)%0A%20%20%20%20at%20p%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.1%2Fangular.min.js%3A7%3A255)%0A%20%20%20%20at%20e%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.1%2Fangular.min.js%3A28%3A427)%0A%20%20%20%20at%20Yb%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.1%2Fangular.min.js%3A32%3A462)
Angular throws this error when it fails to load any module.
In your example, there is a typo in ui.router. You added extra blank space before the module name which may throwing error.
Edit:
The error you copied shows that you are using module named as sun.scrollable is not loaded. Are you loading required module js file??

cordova plugin hotspot module error angularjs

I have taken the sample project from the cordova-plugin-hotspot and tried building it into android application. But when I'm using that sample, I'm getting the module not defined error but I checked that the module has been defined in the html and in angular.module. So please someone help me to figure out what is the actual error. Below is that sample program.
index.html
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-app = "starter">
<!--
The nav bar that will be updated as we navigate between views.
-->
<ion-nav-bar class="bar-stable" ng-controller = "HotSpotCtrl">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</body>
app.js
function onDeviceReady() {
// bootstrap app:
angular.bootstrap(document, ['starter']);
}
if (window.cordova) {
document.addEventListener('deviceready', onDeviceReady, false);
} else {
onDeviceReady();
}
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.constant('$ionicLoadingConfig', {
template: '<ion-spinner></ion-spinner> <br> Loading '
})
.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
// places them at the bottom for all OS
$ionicConfigProvider.tabs.position('bottom');
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
.state('tab.hotspot', {
url: '/hotspot',
views: {
'tab-hotspot': {
templateUrl: 'templates/tab-hotspot.html',
controller: 'HotSpotCtrl'
}
}
})
.state('tab.devices', {
url: '/devices',
views: {
'tab-devices': {
templateUrl: 'templates/tab-devices.html',
controller: 'DevicesCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/hotspot');
});
controller.js
angular.module('starter.controllers', [])
.controller('HotSpotCtrl', function ($scope, $ionicLoading, $timeout) {
var init = function () {
$ionicLoading.show();
// default to WPA2PSK
$scope.config = {
mode: 'WPA2PSK'
};
cordova.plugins.hotspot.isHotspotEnabled(function (enabled) {
$scope.isHotSpotActive = enabled;
$ionicLoading.hide();
}
);
};
// init controllers
init();
// API
$scope.start = function () {
$ionicLoading.show();
cordova.plugins.hotspot.createHotspot(
$scope.config.ssid, $scope.config.mode, $scope.config.password,
function () {
// delay UI refresh
$timeout(function () {
$ionicLoading.hide();
init();
}, 500);
}, function () {
$ionicLoading.hide();
alert('Hotspot creation failed');
}
);
};
$scope.stop = function () {
$ionicLoading.show();
cordova.plugins.hotspot.stopHotspot(
function () {
$ionicLoading.hide();
$scope.isHotSpotActive = false;
init();
}, function () {
alert('AP disabling failed');
}
);
};
})
.controller('DevicesCtrl', function ($scope) {
var init = function () {
cordova.plugins.hotspot.isHotspotEnabled(function (enabled) {
$scope.isHotSpotActive = enabled;
if (enabled) {
$scope.status = 'Reading devices ...';
cordova.plugins.hotspot.getAllHotspotDevices(
function (response) {
$scope.status = false;
$scope.devices = response;
}, function () {
$scope.status = false;
alert('Device listing failed.');
}
);
}
}, function () {
$scope.status = false;
}
);
};
// init controllers
init();
// API
$scope.refresh = function () {
init()
};
});

Scope of all controllers not saving in the service in routing -Angularjs

I'm new to angular js. I was trying to save and share the scope of two different controllers.
Below is my script and views.
script.js:
var app = angular.module('app', ['ngRoute']);
app.run(function ($rootScope) {
$rootScope.$on('scope.stored', function (event, data) {
console.log("scope.stored", data);
});
});
app.controller('FirstController', function($scope) {
$scope.counter = 0;
$scope.add = function(amount) { $scope.counter += amount; };
$scope.subtract = function(amount) { $scope.counter -= amount; };
});
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/v1', {
templateUrl: 'views/v1.ejs',
controller: 'controller1'
}).
when('/v2', {
templateUrl: 'views/v2.ejs',
controller: 'controller2'
})
}]);
app.controller('controller1', function($scope,Scopes) {
Scopes.store('controller1',$scope);
$scope.data = "controller1";
$scope.buttonClick = function () {
console.log( Scopes.get('controller2').data);
};
});
app.controller('controller2', function($scope,Scopes) {
Scopes.store('controller2',$scope);
$scope.data = "controller2";
$scope.buttonClick = function () {
console.log( Scopes.get('controller1').data);
};
});
app.factory('Scopes', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
$rootScope.$emit('scope.stored', key);
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
index.html:
<!doctype html>
<html ng-app="app">
<head>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/script.js"> </script>
</head>
<body>
<a href='#v1'>View1</a>
<a href='#v2'>View2</a>
<div ng-view>
</div>
</body>
</html>
v1.ejs:
<div ng-controller="controller1">
{{data}}
<br>
<button ng-click="buttonClick()">Clickme!</button>
</div>
v2.ejs:
<div ng-controller="controller2">
{{data}}
<br>
<button ng-click="buttonClick()">Clickme!</button>
</div>
The problem is:
Whenever the page is loaded, #/v1 is triggered.
If i click on 'Clickme', JUST AFTER THE PAGE LOADS, Error: Scopes.get(...) is undefined is fired.
But, if i navigate to #/v2 and then to #/v1, the scopes are getting stored and the error is NOT fired.
Is there is some problem with with routeProvider? All the controllers wont be loaded at on-load event?
Please help me on this.

click event not working with angular JS and Require JS

I am working on an application in which I am trying to load angular JS using require JS. My click event is not working in my code. Can someone pls help :
<!DOCTYPE html>
<html lang="en" data-ng-app="myApp">
<body class="internal" >
<div id="contentContainer" class="stratum" data-ng-controller="appController">
<div id="main-bar" class="row">
<div id="go" class="column column.one-quarter-">
<div class="btnLabel"><label for="submitBtn"></label></div>
<div><button id="submitBtn" ng-click="getBarChartData()"> GO</button></div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
var contextPath = "<%= request.getContextPath() %>";
var appUrl = "<%= request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() %>";
var isSessionExpired = false;
</script>
<!-- JavaScripts Require JS Library and App JS Files -->
<script type="text/javascript" data-main="<%=request.getContextPath() %>/resources/js/app/uptimeReport.js" src="<%=request.getContextPath() %>/resources/js/libs/requirejs/require.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/resources/js/app/main-built.js"></script>
</body>
</html>
App.js
/*global require*/
'use strict';
require([
'angular'
], function (angular) {
require([
'controller/environmentController'
], function (appCtrl) {
angular.
module('myApp',[]).
controller('appController', appCtrl);
angular.bootstrap(document, ['myApp']);
console.log("in App.js");
});
});
uptimeReport.js
/*global require*/
'use strict';
requirejs.config(
{
/** set up any additional paths that are outside of your application base * */
paths:
{
angular: contextPath + '/resources/js/libs/angularJS/angular',
},
/**
* The following is not required in this example, but it is an example of
* how to make non-AMD java script compatible with require
*/
shim: {
angular: {
exports: 'angular'
}
},
deps: ['app']
});
controller/environmentController.js
/*global define*/
'use strict';
/**
* The main controller for the app. The controller:
* - retrieves and persist the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
define([
'angular'
], function (angular) {
return ['$scope', '$http',
function($scope, $http) {
console.log("in controller123.js");
var businessUrl="http://localhost:8080/UptimeReport/services/getBusinessAreas";
var appUrl="http://localhost:8080/UptimeReport/services/getApplications";
var envUrl="http://localhost:8080/UptimeReport/services/getEnvironments";
$http.get(businessUrl).then(function(response) {
$scope.business = response.data;
});
$http.get(appUrl).then(function(response) {
$scope.application = response.data;
});
$http.get(envUrl).then(function(response) {
$scope.environment = response.data;
});
}];
});
you should bind the getBarChartData function in your $scope
to be able to use event bind
ng-click="getBarChartData()"
if you did not bind the function to the $scope you can use it like
ng-click="Controller.getBarChartData()"

how to bind click event in angular js using requirejs?

could you please tell me how to bind click event using require js + angularjs
I try to bind the click event but it is bind the click event
Here is my code
index.html
<!DOCTYPE html>
<html>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<head>
<link type="text/css" href="http://code.ionicframework.com/1.0.0-beta.1/css/ionic.css" rel="stylesheet" />
</head>
<body>
<ion-nav-view animation="slide-left-right"></ion-nav-view>
<script data-main="main" src="lib/require.js"></script>
</body>
</html>
main.js
requirejs.config({
paths: {
ionic:'lib/ionic.bundle'
},
shim: {
ionic : {exports : 'ionic'}
}, priority: [
'ionic'
],
deps: [
'bootstrap'
]
});
bootstrap.js
/*global define, require, console, cordova, navigator */
define(['ionic', 'app', 'routes'], function (ionic, angular, app) {
'use strict';
var $html,
onDeviceReady = function () {
angular.bootstrap(document, [app.name]);
};
document.addEventListener("deviceready", onDeviceReady, false);
if (typeof cordova === 'undefined') {
$html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function () {
try {
angular.bootstrap(document, [app.name]);
} catch (e) {
console.error(e.stack || e.message || e);
}
});
}
});
app.js
/*global define, require */
define(['ionic'],
function (angular) {
'use strict';
var app = angular.module('app', [
'ionic']);
return app;
});
You have a few bugs in your code... too many too list them all. See Plunker for the corrections.
The module ionic should be exported as angular.
requirejs.config({
paths: {
ionic:'lib/ionic.bundle'
},
shim: {
ionic : {exports : 'angular'}
}, priority: [
'ionic'
],
deps: [
'bootstrap'
]
});
Ionic/Angular must be loaded first - or angular can't initialize itself.
In the routes you have to reference the controller by name - not by location
/*global define, require */
define(['app'], function (app) {
'use strict';
app.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: "/login",
templateUrl: "login.html",
controller: 'controllers/LoginCtrl' // <-- should be 'LoginCtrl'
})
$urlRouterProvider.otherwise("/login");
}]);
});

Resources