Sharing data between pages in ionic - ionic-framework

I am working on an ionic project.I want to share data between pages. Below is what I have done. But it is not working.Can some one tell me what I am doing wrong.I let the user to add the data to my reminder.html page and I want to show that added data in my meds.html.
This is my services.js
.factory('Authorization', [function() {
authorization = {};
authorization.drug = "";
return authorization;
}]);
This is my controller.js
.controller('reminderCtrl', ['$scope', '$stateParams','Authorization'
function ($scope, $stateParams,Authorization) {
//$scope.user = Authorization;
}])
.controller('medsCtrl', ['$scope', '$stateParams','Authorization',
function ($scope, $stateParams,Authorization) {
//$scope.user = Authorization;
}])
This is my app.js
controller('medsCtrl', function($scope, Authorization) {
$scope.user = Authorization;
})
.controller('reminderCtrl', function($scope, Authorization) {
$scope.user = Authorization;
})
This is my reminder.html. The page that I used to add data.
<button class="button button-royal icon ion-android-done" ng-click = "add(user)" ></button>
</ion-nav-buttons>
<ion-content padding="true" class="has-header">
<form id="reminder2-form7" class="list">
<label class="item item-input" id="reminder2-input9" >
<input type="text" placeholder="Drug" ng-model = "user.drug" >
</label>
This is my meds.html page .This is the page that I want to show the data that I was added to the reminder.html.
<ion-view title="Meds" id="page14">
<ion-nav-buttons side="right" class="has-header">
<button class="button button-royal icon ion-android-add-circle"></button>
</ion-nav-buttons>
<ion-content padding="true" class="has-header">
<ion-list id="meds-list6">
<label class="item item-input" id="meds-search3">
<i class="icon ion-search placeholder-icon"></i>
<input type="search" placeholder="med name">
</label>
<ion-item class="item-thumbnail-left dark" id="meds-list-item21">
<img src="img/CynoZgjCQlSOdh14y24s_drug-disposal.jpg">
<h2dark>Metformin
<p>for diabetes</p>
</h2dark>
</ion-item>
<ion-item class="item-thumbnail-left" id="meds-list-item22">
<img src="img/ZVN6KzlgTP2WdrghQtCH_images.jpg">
<h2>Drug:{{user.drug}}</h2>
</ion-item>
</ion-list>
<a ui-sref="medDiary2" id="meds-button7" class="button button-royal button-clear icon ion-android-add-circle"></a>
<a ui-sref="searchMeds" id="meds-button10" class="button button-royal button-clear icon ion-android-search"></a>
<a ui-sref="reminder" id="meds-button25" class="button button-royal button-clear icon ion-android-alarm-clock"></a>
</ion-content>
</ion-view>

You can use $broadcast in reminderCtrl controller
$scope.addData = function () {
var addObj = {};
// your logic here
$rootScope.$broadcast('add-event', { addedObject: addObj });
}
and listen back to previous event using $on in medsCtrl controller
$scope.$on('add-event', function(event, args) {
var addedObject = args.addedObject;
// Do what you want to do with passed object
console.log(addedObject)
});

Related

Ionic - show splash screen until the first image loads

I have an app in Ionic v.1 and on page where I have a list of articles, I would like to have a splash screen until the first image is completely loaded, not sure how to do that?
This is the controller:
module.exports = angular.module('coop.controllers')
.controller('ArticlesController', function($scope, ArticleService, $state, $ionicScrollDelegate, $location, $ionicPosition, $ionicConfig) {
$scope.articles = ArticleService.all();
$scope.$on('$ionicParentView.afterEnter', function(event, data) {
$scope.videoPlaying = [];
$ionicConfig.views.swipeBackEnabled(false);
if (data.direction == 'back') {
$scope.doRefresh();
}
});
$scope.articleType = 'all';
$scope.articleFilter = function(button) {
$scope.articleType = button;
$scope.doRefresh();
};
$scope.showBulletPoint = function(which) {
return $scope.articleType == which;
}
$scope.like = function(article){
article.userLiked = !article.userLiked;
ArticleService.like(article)
};
$scope.doRefresh = function (){
var articleType = $scope.articleType ? $scope.articleType : 'all';
ArticleService[articleType]().$promise.then(function(data){
$scope.articles = data;
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
};
$scope.videoPlaying = [];
$scope.playerVars = {
controls: 0,
showinfo: 0
};
$scope.playVideo = function(youtubePlayer, index) {
$scope.videoPlaying[index] = true;
youtubePlayer.playVideo();
};
$scope.$on('$ionicView.afterLeave', function(event, data) {
$scope.videoPlaying = false;
$ionicConfig.views.swipeBackEnabled(true);
//youtubePlayer.stopVideo();
});
});
And this the html:
<ion-view>
<div class="row articles-header">
<button menu-toggle="left" class="button button-icon icon ion-navicon-round"></button>
<div class="right-icons">
<!--<a class="button button-icon icon ion-ios-search-strong">
</a>-->
<a class="button button-icon" href="#" ng-click="articleFilter('all')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('all')"></i> Siste
</a>
<a class="button button-icon" href="#" ng-click="articleFilter('video')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('video')"></i> Video
</a>
<a class="button button-icon" href="#" ng-click="articleFilter('popular')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('popular')"></i> Populært
</a>
</div>
</div>
<ion-content class="articles-content">
<ion-refresher pulling-icon="false" on-refresh="doRefresh()">
</ion-refresher>
<ion-list>
<ion-item ng-repeat="article in articles" class="item-light">
<div class="article">
<a ng-if="authenticated" ng-show="article.external_media.length == 0" ui-sref="main.article({id: article.id})" nav-direction="forward" class="article-image-link">
<img class="img" src="{{ fileServer }}/imagecache/cover/{{article.cover_image}}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
</a>
<a ng-if="!authenticated" ng-show="article.external_media.length == 0" ui-sref="main.articlePublic({id: article.id})" nav-direction="forward" class="article-image-link">
<img class="img" src="{{ fileServer }}/imagecache/cover/{{article.cover_image}}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
</a>
<a ui-sref="main.article({id: article.id})">
<div class="iframe" ng-show="article.external_media.length > 0 && article.external_media.image != ''">
<img class="img" ng-src="{{ article.external_media[0].image }}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
<div class="iframe-overlay">
<div class="play">
<img class="playButton" src="icons/playRectangle.svg"/>
</div>
</div>
</div>
</a>
</div>
<div class="row article-meta" ng-class="{ 'has-comments': article.enable_comments }">
<a ng-click="like(article)" class="subdued col col-30">
<img class="social-images" ng-src="icons/{{ article.userLiked ? 'heart' : 'heart-outline' }}.svg"/> Lik
</a>
<a ui-sref="main.article({id: article.id, gotoComments: true })" class="subdued col col-60" ng-if="article.enable_comments">
<img class="social-images" src="icons/comment.svg"/> {{ article.commentCount }} Kommentarer
</a>
<a ui-sref="main.article({id: article.id})" nav-direction="forward" class="col col-10 article-link right">
<img class="social-images" src="icons/arrow.svg"/>
</a>
</div>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
One approach is to attach an onLoad handler to the images, and when the first image (or any other specific image, all, etc) have loaded you can remove your splash screen.
To do this we'll create a directive to handle the onload event, based on this outstanding solution from Peter, combined with the $ionicLoading loader.
var app = angular.module('app', ['ionic'])
app.controller('appCtrl', function($scope, $timeout, $ionicLoading) {
// Setup the loader
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
// Add a simple onLoad callback
$scope.onLoad = function (id) {
if (id === 0) {
$ionicLoading.hide();
}
}
$scope.items = [
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'},
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'},
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'}
];
});
// The imageonload directive
app.directive('imageonload', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
//call the function that was passed
scope.$apply(attrs.imageonload);
});
}
};
})
Then use the directive:
<ion-item ng-repeat="item in items" href="#">
<img ng-src="{{item.img}}" imageonload="onLoad({{$index}})" id="img-{{$index}}" />
</ion-item>
When the app loads the $ionicLoading screen will be shown until the first image emits the onload event, causing the $ionicLoading screen to be removed.
For a working demo, see this Ionic Play demo.
The loading screen may only be noticeable the first time you load the demo, and on subsequent loads you might need to do a hard refresh.

pull to refresh in ionic does not refresh my list

Using ionic pull to refresh function does not update my list. Function is called and in console data is retrieved from serve but does not refresh my list.
here is my view:
<ion-list>
<ion-item class="list card" ng-repeat="pickup in pickups">
<div class="item">
<h2>{{pickup.title}}</h2>
<p>Request Date : {{pickup.added_date}}</p>
<p>Status :
<span class="positive" ng-if="pickup.status==0">On Queue</span>
<span class="energized" ng-if="pickup.status==1">On Process</span>
<span class="balanced" ng-if="pickup.status==2">On Collected</span>
<span class="assertive" ng-if="pickup.status==2">Cancelled</span>
</p>
</div>
<div class="item item-body">
<p>Contact : {{pickup.b_contact}}</p>
<p>Location : {{pickup.b_location}}</p>
<p>
<a class="button circular-btn icon ion-android-done button-energized" href="#"
ng-click="statusData(pickup.pickupid,pickup.user_id,1)"
ng-if="pickup.status==0"></a>
<a class="button circular-btn ion-android-done-all button-balanced" href="#"
ng-click="statusData(pickup.pickupid,pickup.user_id,2)"
ng-if="pickup.status==0|| pickup.status==1"></a>
<a class="button circular-btn icon ion-close-circled button-assertive" href="#"
ng-click="statusData(pickup.pickupid,pickup.user_id,3)"
ng-if="pickup.status==0|| pickup.status==1|| pickup.status==2"></a>
</p>
</div>
</ion-item>
</ion-list>
</ion-content>
my controller code:
.controller('AppCtrl', function ($scope, Service, $ionicLoading, $ionicModal, $ionicPopup, $timeout, $state, $http, $stateParams) {
$scope.doRefresh = function () {
Service.getpickup($state, $http).success(function (data) {
$scope.pickups = data.pickup_request;
console.log(data.pickup_request);
})
.finally(function () {
$scope.$broadcast('scroll.refreshComplete');
});
}
});
Please guide me. Thanks in advance.
Have you used the ion-refresher tag in your html? I cant see it in your code. If not, use this
<ion-refresher pulling-text="Pull to refresh..." on-refresh="doRefresh()">
Also, try manually adding the items to your list like this and see if that works. (check that data.pickup_request is an array as well)
$scope.pickups.push.apply($scope.pickups, data.pickup_request);
I have found the issues. I have the view in pickupCtrl but i was calling the scope function in another control. Thank you every one for your guide.Thanks a lot.

how to show total notification count in ionic app

Am developing app using ionic framework as a frontend and php-mysql as a backend.
Implemented the push notification using google GCM.
Am receiving push notification when anything added in backend.
Required to implement following feature:
Show the number of notification received above the app icon in home screen.
Answers will be much appreciated..
ionic push notification sample https://github.com/hollyschinsky/PushNotificationSample
Badge Is Count for how `much notification successfully send.`
var buildPayload = function (options) {
var notif = new apn.Notification(options.payload);
notif.expiry = options.expiry || 0;
notif.alert = options.alert;
notif.badge = options.badge;
notif.sound = options.sound;
return notif;
};
if (notification.badge) {
$cordovaPush.setBadgeNumber( notif.badge).then(function (result) {
console.log("Set badge success " + result)
}, function (err) {
console.log("Set badge error " + err)
});
}
Create a rootScope variable notificationCount and increment the value of this variable For every notification
Controller
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
if (notification.badge) {
$cordovaPush.setBadgeNumber(notification.badge).then(function(result) {
$rootScope.notificationCount = notification.badge;
}, function(err) {});
}
});
HTML
<ion-side-menus enable-menu-with-back-views="false">
<ion-side-menu-content>
<ion-nav-bar class="bar-light" align-title="left">
<ion-nav-back-button>
</ion-nav-back-button>
<ion-nav-buttons side="left">
<button class="button button-icon button-clear ion-navicon" menu-toggle="left">
</button>
</ion-nav-buttons>
<ion-nav-buttons side="right">
<button class="button button-icon home-notification-icon button-clear ion-ios-home" ng-click="openHome()">
</button>
<button class="button button-icon button-clear home-notification-icon ion-android-notifications" badge="5" badge-style="badge-assertive">
<span class="badge notification-badge badge-assertive header-badge">{{notificationCount}}</span>
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-nav-view name="menuContent"></ion-nav-view>
</ion-side-menu-content>
<ion-side-menu side="left" style="background-color: #383839;">
<ion-header-bar class="bar-stable">
<img src="img/logo-web.png">
</ion-header-bar>
<ion-content id="sidemenu">
<!-- Your content goes here -->
</ion-content>
</ion-side-menu>
</ion-side-menus>

Ionic Return value navigation on different view

I have a form view with an input text. When I click on this input, another view is opened.
In this view, there are an input search and a list. The list change when I change a text from the input search.
I want when I click one item of the list, this view gets closed and the input text change. But I don't know how I can do that.
Can you help me please?
the input text in my form view:
<div class="select-typeevent">
<ion-item nav-clear menu-close ui-sref="menu.setlocation">
<label class="padding">
Address:
</label>
</ion-item>
</div>
My searchview:
<ion-view view-title="Address" class="content">
<ion-content>
<h1>Address</h1>
<div class="bar bar-header item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios-search placeholder-icon"></i>
<input class="border-none" name="txtssearch" type="search" placeholder="Search" ng-model="addresssearch" ng-change="getGeocode(addresssearch)">
</label>
<button class="button button-clear" ng-click="addresssearch='';getGeocode(addresssearch)">
Annuler
</button>
</div>
<div class="list" >
<a ng-repeat="addr in addresslist" class="item" ng-click="setaddress(addr)">
{{addr.address}} {{addr.location}}
</a>
</div>
</ion-content>
</ion-view>
And the js:
'Use Strict';
angular.module('App').controller('setlocationController', function ($scope,$state, $cordovaOauth, $localStorage, $location, $http, $ionicPopup,$firebaseObject,$ionicHistory, Auth, FURL, Utils) {
$scope.getGeocode = function (addresssearch) {
$scope.geodata = {};
$scope.queryResults = {};
$scope.queryError = {};
$http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + addresssearch)
.then(function (_results) {
$scope.addresslist = [];
$scope.queryResults = _results.data.results;
console.log($scope.queryResults);
$scope.queryResults.forEach(function(result) {
$scope.addresslist.push({ 'address': result.formatted_address, 'location': result.geometry.location });
});
},
function error(_error){
$scope.queryError = _error;
})
};
// Here I want when I click one item of the list, this view gets closed and the input text of formview change.
$scope.setaddress = function (addr) {
$scope.setaddress = addr;
$ionicHistory.backView();
}
Why not using an $ionicModal:
$scope.getGeocode = function (addresssearch) {
...
$scope.modal.show();
}
Previously set the modal:
$ionicModal.fromTemplateUrl('my-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
Where my-modal.html points to the template which shows geocode information.

Ionic scroll won't fire on load with $getByHandle()

I'm trying to scroll down to delegate-handle="start" with ionic on load. When i try to run it, i get this message in console.
Delegate for handle "small" could not find a corresponding element with delegate-handle="small"! scrollTop() was not called!
Possible cause: If you are calling scrollTop() immediately, and your element with delegate-handle="small" is a child of your controller, then your element may not be compiled yet. Put a $timeout around your call to scrollTop() and try again.
My code looks like this, can somebody maybe see what is wrong?
$timeout(function() {
$ionicScrollDelegate.$getByHandle('start').scrollTop();
}, 10);
If i use $ionicScrollDelegate.scrollBottom(), it will scroll to the bottom, so it must be a problem with the specific function.
The html code
<ion-view title="Kalender">
<ion-content>
<ion-list ng-repeat="activity in calendar">
<div class="item item-divider" ng-show="activity.date_divider != null" data-year="{{activity.year}}">
<div class="header-divider-small">{{activity.year}}</div>
<div class="header-divider">{{activity.date_divider}}</div>
</div>
<div class="item item-icon-right calendar" ng-show="activity.date_divider == null">
<span class="header">{{activity.name}}</span>
<br />
<span class="text">{{activity.time}} - {{activity.place}}</span>
<a class="button button-icon icon {{activity.icon}} right not-selected"></a>
</div>
</ion-list>
<div delegate-handle="start"></div>
</ion-content>
</ion-view>
Thanks.
Ionic 1.0.0-beta14 has some strange issue with getByHandle() so you can do it this way:
$timeout(function() {
var startHandle = _.find($ionicScrollDelegate._instances, function (s) {
return s.$$delegateHandle === "start";
});
startHandle.scrollTop();
});
Solution source at forum.ionicframework.com
I think there is a misunderstanding about what the delegate handle does here. Delegate handle is a way to name scroll/content containers. Think of it like a way to give your <ion-content> container a unique name that can be later used with the service. It is possible to have multiple <ion-content> containers on a single view, and this is why the naming is necessary. If you only have one scroll area or don't specify the handle, then it just uses the first view it finds.
You want to scroll to a particular place in the application, which is the job of $ionicScrollDelegate.anchorScroll('element-id');. Take a look at your code here with some modifications. I've put the delegate handle in the correct place, and then use the anchorScroll method to automatically scroll to that ID in the page.
Markup
<ion-view title="Kalender">
<ion-content delegate-handle="kalendar">
<ion-list ng-repeat="activity in calendar">
<div class="item item-divider" ng-show="activity.date_divider != null" data-year="{{activity.year}}">
<div class="header-divider-small">{{activity.year}}</div>
<div class="header-divider">{{activity.date_divider}}</div>
</div>
<div class="item item-icon-right calendar" ng-show="activity.date_divider == null">
<span class="header">{{activity.name}}</span>
<br />
<span class="text">{{activity.time}} - {{activity.place}}</span>
<a class="button button-icon icon {{activity.icon}} right not-selected"></a>
</div>
</ion-list>
<div id="start"></div>
</ion-content>
</ion-view>
Controller
$timeout(function() {
$ionicScrollDelegate.$getByHandle('kalendar').anchorScroll('start');
}, 10);
Specify the dalegate-handler in ion-content
<ion-view title="Kalender">
<ion-content delegate-handle="start">
<ion-list ng-repeat="activity in calendar">
<div class="item item-divider" ng-show="activity.date_divider != null" data-year="{{activity.year}}">
<div class="header-divider-small">{{activity.year}}</div>
<div class="header-divider">{{activity.date_divider}}</div>
</div>
<div class="item item-icon-right calendar" ng-show="activity.date_divider == null">
<span class="header">{{activity.name}}</span>
<br />
<span class="text">{{activity.time}} - {{activity.place}}</span>
<a class="button button-icon icon {{activity.icon}} right not-selected"></a>
</div>
</ion-list>
</ion-content>
</ion-view>
Scroll top can be achieved by forgetting the scroll position which can be achieved by using
$scope.$on("$destroy", function() {
var delegate = $ionicScrollDelegate.$getByHandle('start');
delegate. forgetScrollPosition();
});
Use
$ionicScrollDelegate.$getByHandle('start').scrollTop(); //To scroll to Top.
As I noticed delegate-handle won't work if used with overflow-scroll.
I managed to do it this way:
$scope.scrollHandle = some-handle-value-that-you-want-to-use;
$scope.$on('$ionicView.loaded', function () {
$timeout(function () {
scrollView = $ionicScrollDelegate._instances.filter(function (s) {
if (!s.$$delegateHandle) return false;
return $parse(s.$$delegateHandle.slice(2, -2))
(angular.element(s.element).scope()) == $scope.scrollHandle;
})[0];
}).then(function () {
scrollView.scrollTo(0, 0, false);
});
});
In the template:
delegate-handle="{{scrollHandle}}"
EDIT:
This doesn't work anymore, check this answer for new solution: https://stackoverflow.com/a/32123613/1630623