LocalNotification when the page open - javascript

I have an issue that i don't know how to solve it. My localNotification is working great with a button but what I need is when the page open, call the notification function automatically, how do I do that?
angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers'])
//enter code here
.run(function($ionicPlatform, $rootScope) {
$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.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
$rootScope.$on('$cordovaLocalNotification:schedule',
function (event, notification, state) {
console.log("SCHEDULE");
console.log('event', event);
console.log('notification', notification);
console.log('state', state);
});
$rootScope.$on('$cordovaLocalNotification:trigger',
function (event, notification, state) {
console.log("TRIGGER");
console.log('event', event);
console.log('notification', notification);
console.log('state', state);
});
$rootScope.$on('$cordovaLocalNotification:update',
function (event, notification, state) {
console.log('UPDATE');
console.log('event', event);
console.log('notification', notification);
console.log('state', state);
});
$rootScope.$on('$cordovaLocalNotification:cancel',
function (event, notification, state) {
console.log('CANCEL');
console.log('event', event);
console.log('notification', notification);
console.log('state', state);
});
});
})
.controller('SampleController',
function ($scope, $cordovaLocalNotification, $ionicPlatform) {
$ionicPlatform.ready(function () {
$scope.scheduleInstantNotification = function () {
$cordovaLocalNotification.schedule({
id: 1,
text: 'Instant Notification',
title: 'Instant'
}).then(function () {
alert("Instant Notification set");
});;
};
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templatesInfo/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templatesInfo/search.html'
}
}
})
.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templatesInfo/browse.html'
}
}
})
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templatesInfo/playlists.html',
controller: 'PlaylistsCtrl'
}
}
})
.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'templatesInfo/playlist.html',
controller: 'PlaylistCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
});
View:
<ion-view view-title="Information">
<ion-content>
<div class="list card" >
<div class="item item-avatar" >
<h2>Dr. Therese Ouellet</h2>
<p>Agriculture and Angri food Canada</p>
</div>
<div class="item item-body">
<img class="full-image" src="img/therese.jpg">
<p>
This is a "Facebook" styled Card. The header is created from a Thumbnail List item,
the content is from a card-body consisting of an image and paragraph text. The footer
consists of tabs, icons aligned left, within the card-footer.
</p>
</div>
</div>
<button class="button button-block button-positive" ng-click="scheduleInstantNotification()">
Instant
</button>
</ion-content>
</ion-view>

You can use $ionicView.enter event in your $scope to run specific code right after the view/page has fully entered and is now the active view.
This event will fire, whether it was the first load or a cached view
Your new SampleController:
.controller('SampleController',
function ($scope, $cordovaLocalNotification, $ionicPlatform) {
$ionicPlatform.ready(function () {
$scope.scheduleInstantNotification = function () {
$cordovaLocalNotification.schedule({
id: 1,
text: 'Instant Notification',
title: 'Instant'
}).then(function () {
alert("Instant Notification set");
});;
};
$scope.$on("$ionicView.enter", function(event, data){
// handle event
$scope.scheduleInstantNotification();
});
});
})
Checkout full details here: ionView

Related

Adding hardware Back button to Home for Ionic in android

Ionic has a different navigation when press a function from side menu. When you press a back button from handset, it will straight away exit.
I refer to this tutorial and make the changes to my app.js but it unable to back to home page but exit the app.
The code suppose to (which is what I needed):
1.if not at home page, it will back to previous page if press hardware back button
2.if it is at home page, press hardware back button will show pop up to confirm if user really want to exit.
app.js
angular.module('myapp', ['ionic', 'myapp.controllers', 'myapp.factories'])
.run(function($ionicPlatform,$state,$ionicHistory,$ionicPopup) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
$ionicPlatform.registerBackButtonAction(function (event) {
event.preventDefault();
if ($state.current.name == "app.home") {
var confirmPopup = $ionicPopup.confirm({
title: 'Exit',
template: 'Confirm Exit'
});
confirmPopup.then(function (res) {
if (res) {
navigator.app.exitApp();
}
});
} else {
$ionicHistory.nextViewOptions({ disableBack: true });
$state.go('app.home');
}
}, 100);//registerBackButton
});
})
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'menuCtrl'
})
.state('app.home', {
url: '/home',
views: {
'menuContent': {
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
}
}
})
.state('app.personalitem', {
url: '/personalitem',
views: {
'menuContent': {
templateUrl: 'templates/personalitem.html',
controller: 'personalitemCtrl'
}
}
})
.state('app.pStock', {
url: '/pStock',
views: {
'menuContent': {
templateUrl: 'templates/pStock.html',
controller: 'pStockCtrl'
}
}
});
angular.module('myapp.factories', []);
angular.module('myapp.controllers', []);
How shall I do with my code so that I can get the hardware back button work?
Can you try:
menu.ts openPage(page) {
this.nav.setRoot(page.component);
}
menu.html <button class="menuList" menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
{{p.title}}
</button>
app.component.ts pages: any[] = [
{ title: 'Welcome', component: IntroPage },
{ title: 'Home', component: TabsPage },
]

How to angularjs pagination using $http

I am trying to create a pagination using Angularjs in Ionic Framework. Please help me to write code of pagination. I am getting data form this json url.
controller.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
// Form data for the login modal
$scope.loginData = {};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
console.log('Doing login', $scope.loginData);
// Simulate a login delay. Remove this and replace with your login
// code if using a login system
$timeout(function() {
$scope.closeLogin();
}, 1000);
};
})
.controller('PlaylistsCtrl', function($scope, $http, $log) {
$http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
.then(function(response)
{
$scope.data = response.data;
});
})
.controller('PlaylistCtrl', function($scope, $stateParams) {
});
app.js
// Ionic Starter App
// 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.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.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html'
}
}
})
.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templates/browse.html'
}
}
})
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templates/playlists.html',
controller: 'PlaylistsCtrl'
}
}
})
.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'templates/playlist.html',
controller: 'PlaylistCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
});
playlists.html
<ion-view view-title="Playlists">
<ion-content>
<ion-list>
<ion-item ng-repeat="playlist in data | firstPage:currentPage*pageSize | limitTo:pageSize" href="#/app/playlists/{{playlist.id}}">
{{playlist.title}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
<< 1/2/3/4/5 >>
You need to set pageSize to the total number of movies returned as the response does not contain any meta data about the response:
.controller('PlaylistsCtrl', function($scope, $http, $log) {
$http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
.then(function(response)
{
// populate data with the array of movies
$scope.data = response.data;
// set the page size to the total number of movies
$scope.pageSize = $scope.data.length;
});
});

Using $state.go() with onResume()

I am trying to redirect to my login page each time my application comes from background to foreground but I get that error :
Uncaught TypeError: $state.go is not a function
So I obviously did something wrong, but I can't get what.
Here is some parts of my code in my app.js :
// Ionic Starter App
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('resetLogin', {
url: '/resetLogin',
templateUrl: 'templates/resetLogin.html',
controller: 'ResetLoginCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
$urlRouterProvider.otherwise('/login');
})
.run(function($ionicPlatform, $state) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
function onDeviceReady() {
}
});
document.addEventListener("resume", onResume, false);
function onResume($state){
$state.go('login');
}
Juste move your function in the block run and remove $state in the onResume.
Only angular function are injectable. In fact you're probably getting an event object in your case but surely not the $state.
.run(function($ionicPlatform, $state) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
function onDeviceReady() {
}
document.addEventListener("resume", onResume, false);
function onResume(){
$state.go('login');
}
});

angular controller doesnt get called or instantiated

I am trying to call a function in another controller from a different controller but but I keep getting error
Error: [ng:areq] Argument 'NewCaseCtrl' is not a function, got undefined
My app.js
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'MainCtrl'
})
.state('app.dashboard', {
url: "/dashboard",
views: {
'menuContent': {
templateUrl: "templates/dashboard.html",
}
}
})
.state('app.new', {
url: "/new_referral",
views: {
'menuContent': {
templateUrl: "templates/new_referral.html",
controller: 'NewCaseCtrl'
}
}
})
my dashboard.html
<ion-view view-title="Dashboard">
<ion-content>
<div class="list card">
<div class="item bar bar-royal">Referral Case Updates</div>
<div class="item item-body">
<div ng-controller="NewCaseCtrl" class="ion-ios-plus-outline" ng-click="createNew()"></div>
</div>
</div>
</ion-content>
</ion-view>
my new_referral.html
<ion-view view-title="New Referral">
<ion-nav-bar class="bar-stable">
<ion-nav-buttons side="left">
<button class="button button-small" ng-click = "goBack()">Cancel</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-content>
<p> In new referral page
</ion-content>
</ion-view>
my new_controller.js
angular.module('my.controllers')
.controller('NewCaseCtrl', function($scope, $rootScope, $q, $window, $ionicModal, createNewRealEstateCase, $state, $ionicLoading, $cordovaCamera, $cordovaFile, $cordovaFileTransfer, $ionicSlideBoxDelegate) {
$scope.createNew = function() {
console.log("in here build loan application")
createNewRealEstateCase.buildLoanApplication().then(function(data){
$rootScope.states = data.states;
$rootScope.nationalities = data.nationalities;
var hideSheet = $ionicActionSheet.show({
buttons: [
{ text: 'Eligibility Checking' },
{ text: 'Loan Application' }
],
cancelText: 'Cancel',
titleText: 'Type of Service',
cancel: function() {
// add cancel code..
},
buttonClicked: function(index) {
console.log(index)
if(index == 0) {
$scope.eligibility = true;
}
else if(index == 1){
$scope.eligibility = false;
}
$state.go('app.new')
return true;
}
});
$timeout(function() {
hideSheet();
}, 10000);
});
};
});
Why do i get an error why i click on the createNew() div in dashboard.html when i have already initiated ng-controller="NewCaseCtrl"? why doesnt it work as it should?
Thanks any help appreciated
Instead of nesting controllers you can have a service which shares the data & functions for both the controller.

How to change states when logging in or logging out with firebase without refreshing?

I am trying to use resolve to check for the authentication state and direct the user to the appropriate view.
I am trying the following (see below), but it does not result in transferring to the appropriate states as it would have done when refreshing the page.
app.js
// Ionic Starter App
// 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.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'firebase'])
.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.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.run(["$rootScope", "$state", function($rootScope, $state) {
$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
// We can catch the error thrown when the $requireAuth promise is rejected
// and redirect the user back to the home page
if (error === "AUTH_REQUIRED") {
console.log('stateChangeError')
$state.go("app.login");
}
});
}])
.config(function($stateProvider, $urlRouterProvider) {
var authResolve = {
authReturn: function($state, $q, $timeout, Auth) {
var defer = $q.defer();
var ref = Auth.refObj();
ref.onAuth(authDataCallback)
function authDataCallback(authData) {
if (authData) {
console.log("authDataCallback: User " + authData.uid + " is logged in with " + authData.provider);
defer.resolve(authData)
} else {
console.log("authDataCallback: User is logged out");
defer.reject('AUTH_REQUIRED')
}
}
$timeout(function() { // See: http://stackoverflow.com/q/24945731/247243
defer.reject('login');
}, 250);
return defer.promise;
}
};
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.login', {
url: "/login",
views: {
'menuContent': {
templateUrl: "templates/login.html",
controller: "LoginCtrl"
}
}
})
.state('app.profile', {
url: "/profile",
views: {
'menuContent': {
templateUrl: "templates/profile.html",
resolve: authResolve
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/login'); //CHANGE TO HOME
});
controller.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope) {
})
.controller('LoginCtrl', function($scope, $timeout, $state, Auth) {
var ref = Auth.refObj();
var authData = ref.getAuth();
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
$scope.authData = authData;
} else {
console.log("User is logged out");
}
$scope.signOut = function() {
Auth.signOut();
}
$scope.signIn = function() {
Auth.signIn();
}
})
.factory('Auth', function($firebase, $firebaseAuth, $state) {
// Register the callback to be fired every time auth state changes
var ref = new Firebase("https://lovin.firebaseio.com");
var signIn = function() {
ref.authWithPassword({
email : 'sa.ibisevic#gmail.com',
password : 'Maserati2014'
}, authHandler);
// logging users in
function authHandler(error, authData) {
if (error) {
console.log("Login Failed!", error);
$state.go("app.login")
} else {
console.log("Authenticated successfully with payload:", authData);
$state.go("app.profile")
}
}
}
var signOut = function() {
ref.unauth();
$state.go("app.login")
}
var authRef = function() {
return $firebaseAuth(ref);
}
return {
signIn: signIn,
signOut: signOut,
refObj: function() {
return ref;
},
authRef: authRef
}
})
login.html
<ion-view view-title="Login">
<ion-nav-bar class="bar-stable">
<ion-nav-buttons side="left">
<button class="button button-icon button-clear ion-navicon" menu-toggle="left">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-content>
<h1>{{authData.uid}}</h1>
<button class="button" ng-click="signIn()">Sign In</button>
<button class="button" ng-click="signOut()">Sign Out</button>
</ion-content>
</ion-view>
Beware that you can listen to the authentication state on the $firebaseSimpleLogin object. So you could do something like that:
$rootScope.$on('$firebaseSimpleLogin:logout', function(event) {
$state.go('login');
});
Hope this helps.

Categories

Resources