I am new in angular and ionic framework and building an android app which is a simple todo-list. I am facing few issue in this, when I call edit function an popup appears and when I edit that li it wont save it.Another one is now my popup is not appearing and it giving me following issues
1) http://prntscr.com/d4yj27
2) http://prntscr.com/d4ymm5
I am pasting my complete code please help me
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="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/ngDraggable.js"></script>
</head>
<body ng-app="elegantTodo" ng-controller="todoCntrl">
<ion-pane>
<ion-header-bar class="bar bar-header bar-calm">
<label class="item-input-wrapper">
<input class="ionic-search-bar" ng-model="searchdata" type="search" placeholder="Search">
</label>
<button class="button button-clear" ng-click="searchclear()">
<i class="icon ion-ios-close-empty"></i>
</button>
</ion-header-bar>
<ion-content class="todolist-items" scrollY="true">
<ul class="list draglist">
<li class="item" ng-drag="true" ng-drag-data="x" ng-class="x" ng-repeat="x in todolist | filter:searchdata track by $index" ng-drop="true" ng-drop-success="onDropComplete($index, $data,$event)">
<div class="individual-item" ng-click="editTodo(x)">
{{x}}
</div>
<span ng-click="removeItem($index)"><i class="icon ion-ios-close-empty" ></i></span>
</li>
</ul>
</ion-content>
<ion-footer-bar class="bar bar-footer bar-calm">
<!--p class="error-msg">{{errortext}}</p-->
<label class="item-input-wrapper">
<input type="text" class="ionic-search-bar" ng-model="addMe" placeholder="Add Your Task Here...">
</label>
<button class="button button-clear" ng-click="addItem()">
<i class="icon ion-ios-plus-empty"></i>
</button>
</ion-footer-bar>
</ion-pane>
</body>
</html>
App.js
var app = angular.module('elegantTodo', ['ionic','ngDraggable']);
app.factory('Todo', function() {
return {
all: function() {
var itemlist = window.localStorage['todolist'];
if(itemlist) {
return angular.fromJson(itemlist);
}
return [];
},
save: function(todolist) {
window.localStorage['todolist'] = angular.toJson(todolist);
}
}
});
app.controller("todoCntrl", function($scope, $ionicPopup, Todo){
$scope.todolist = Todo.all();
$scope.addItem = function(){
$scope.errortext = "";
if(!$scope.addMe){return;}
if($scope.todolist.indexOf($scope.addMe) == -1){
$scope.todolist.push($scope.addMe);
Todo.save($scope.todolist);
$scope.addMe = "";
}else{
alert("This task is already exists in your todo List");
}
}
$scope.removeItem = function(index){
$scope.errortext = "";
$scope.todolist.splice(index, 1);
Todo.save($scope.todolist);
}
$scope.searchclear = function(){
$scope.searchdata = "";
}
$scope.editTodo = function(x) {
$scope.data = { response: x }; // A hack to pre-populate prompt
$ionicPopup.prompt({
title: "Edit Task",
scope: $scope
}).then(function(res) { // promise
if (res !== undefined) x = $scope.data.response; // response not res has new title (hack
})
}
$scope.onDropComplete = function (index, x, evt) {
var otherObj = $scope.todolist[index];
var otherIndex = $scope.todolist.indexOf(x);
$scope.todolist[index] = x;
$scope.todolist[otherIndex] = otherObj;
}
});
app.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();
}
});
})
I am totally lost and Please help me where I am doing wrong
Mayank
Related
I am a new to Ionic. I have done some google search but I am still a bit confused.
From my android Ionic app I would like to launch the google map application passing latitude and longitude so that the user can then navigate to the place.
Is is possible? Any help is very appreciated.
Thanks in advance,
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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.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>
</head>
<body ng-app="starter" ng-controller="main">
<div ui-view>
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Login App</h1>
</ion-header-bar>
<ion-content>
<div>
</div>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="data.email">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
</div>
<button class="button button-block button-calm" ng-click="postLogin()">Login</button>
</ion-content>
</ion-pane>
</div>
</body>
</html>
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'
var app = angular.module('starter', ['ionic'])
.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('login', {
url: '/login',
templateUrl: 'index.html',
controller: 'main'
})
.state('userPositionInMap', {
url: '/userPositionInMap',
templateUrl: 'map.html',
controller: 'MapController'
})
$urlRouterProvider.otherwise('/login');
});
app.controller('main', function ($scope,$http,$stateParams,$ionicPopup,$location)
{
$scope.data = {};
$scope.postLogin = function ()
{
var data =
{
email: $scope.data.email,
password: $scope.data.password,
latitude,
langitude
};
$http.post("http://localhost/authproject/public/api/auth/login", data)
.then(
function(response){
// success callback
console.log('success');
data.latitude=response.latitude;
data.langitude=response.langitude;
$location.path("/userPositionInMap");
},
function(response){
// failure callback
console.log('error');
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
}
);
}
});
app.controller('MapController', function ($scope,$stateParams)
{
});
map.html
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBsiDiIzQjg7U9JYPDVl8hnfZ7MwDcHDHg&signed_in=true&libraries=places&callback=initMap" async defer></script>
<script>
function initMap() {
var position = new google.maps.LatLng({lat: 48.85661400000001 , lng: 2.3522220000000177 });
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 48.85661400000001 , lng: 2.3522220000000177 },
zoom: 15
});
var marker = new google.maps.Marker({
position: position,
map: map,
title: ""
});
//var input = document.getElementById('address');
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(myLatlng);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
//anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function () {
marker.setVisible(false);
var place = autocomplete.getPlace();
if (place != undefined) {
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
console.log(place.geometry.location.toString());
$('#lat').val(lat);
$('#lng').val(lng);
}
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
});
}
</script>
<ion-view view-title="Map">
<ion-content class="padding">
<div class="list card">
<div class="item item-divider">Map</div>
<div class="item item-body">
<div id="map" style="width:100%; height:100%;"></div>
</div>
</div>
</ion-content>
</ion-view>
I have a rough idea of what you are tying to achieve. You can wrap your code for the map in a directive, then via the link function you can access $rootScope which you can use to hold the lat and lng from the database. Here is the doc for directives: https://docs.angularjs.org/guide/directive
Try to use Angular-maps : https://angular-maps.com/
#Component({
selector: 'app-root',
styles: [`
agm-map {
height: 300px;
}
`],
template: `
<agm-map [latitude]="lat" [longitude]="lng"></agm-map>
`
})
export class AppComponent {
lat: number = 51.678418;
lng: number = 7.809007;
}
I'm developing a Wordpress Ionic application using the Wordpress REST API and Jetpack. I followed a tutorial Hybrid Mobile Application with Ionic/Cordova, but ran into an ugly problem. When I enter my REST API link in $http.get() and try it in my browser it keeps loading like this:
On the other hand, the Freshy-Pressed Api works, though I don't know why.
Here is the HTML and JavaScript I'm using:
var FPApp = angular.module("FPApp", ["ionic"]);
FPApp.service("FPSvc", ["$http", "$rootScope", FPSvc]);
FPApp.controller("FPCtrl",
["$scope", "$sce",
"$ionicLoading", "$ionicListDelegate", "$ionicPlatform",
"FPSvc", FPCtrl]);
function FPCtrl($scope, $sce, $ionicLoading, $ionicListDelegate, $ionicPlatform, FPSvc) {
$ionicLoading.show({template: "Loading blogs..."});
$scope.deviceReady = false;
$ionicPlatform.ready(function() {
$scope.$apply(function() {
$scope.deviceReady = true;
});
});
$scope.blogs = [];
$scope.params = {};
$scope.$on("FPApp.blogs", function(_, result) {
result.posts.forEach(function(b) {
$scope.blogs.push({
name: b.author.name,
avatar_URL: b.author.avatar_URL,
title: $sce.trustAsHtml(b.title),
URL: b.URL,
featured_image: b.post_thumbnail.URL
});
});
$scope.params.before = result.date_range.oldest;
$scope.$broadcast("scroll.infiniteScrollComplete");
$scope.$broadcast("scroll.refreshComplete");
$ionicLoading.hide();
});
$scope.loadMore = function() {
FPSvc.loadBlogs($scope.params);
}
$scope.reload = function() {
$scope.blogs = [];
$scope.params = {};
FPSvc.loadBlogs();
}
$scope.show = function($index) {
cordova.InAppBrowser.open($scope.blogs[$index].URL, "_blank", "location=no");
}
$scope.share = function($index) {
$ionicListDelegate.closeOptionButtons();
window.socialmessage.send({
url: $scope.blogs[$index].URL
});
}
}
function FPSvc($http, $rootScope) {
this.loadBlogs = function(params) {
$http.get("https://public-api.wordpress.com/rest/v1/sites/100060382/posts/", {
params: params})
.success(function(result) {
$rootScope.$broadcast("FPApp.blogs", result);
});
}
}
<html lang="en" data-ng-app="FPApp">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!--Setup Cordova-->
<meta http-equiv="Content-Security-Policy" content="default-src *;">
<script src="cordova.js"></script>
<!--Setup Ionic-->
<link rel="stylesheet" href="lib/ionic/css/ionic.css">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!--Setup Application-->
<link rel="stylesheet" href="index.css">
<script src="index.js"></script>
</head>
<body data-ng-controller="FPCtrl">
<ion-pane>
<div class="bar bar-header bar-energized">
<h1 class="title">ZahranPress</h1>
</div>
<ion-content class="background">
<ion-refresher pulling-text="Pull" on-refresh="reload()">
</ion-refresher>
<div class="list card" data-ng-repeat="b in blogs">
<div class="item item-avatar">
<img data-ng-src="{{b.avatar_URL}}" alt="">
<h2 data-ng-bind-html="b.title"></h2>
<p> {{ b.name }} </p>
</div>
<div class="item item-body">
<img data-ng-if="b.featured_image" data-ng-src="{{ b.featured_image }}" alt="" class="full-image">
</div>
<div class="item tabs tabs-secondary tabs-icon-left">
<a class="tab-item" data-ng-click="show($index)">
<i class="icon ion-ios-book"></i>
Read
</a>
<a class="tab-item" data-ng-click="share($index)">
<i class="icon ion-share"></i>
Share
</a>
</div>
</div>
<ion-infinite-scroll on-infinite="loadMore()" ng-if="deviceReady"></ion-infinite-scroll>
</ion-content>
</ion-pane>
</body>
</html>
How do I resolve this problem?
Am I am new to firebase and was following a tutorial on creating a simple chat app using ionic however I cannot seem to get the message to return and be displayed.
Here is my Index.html as well as my app.js I cannot seem to find whats wrong.
<!DOCTYPE html>
<html>
<head>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<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>
<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<!-- AngularFire -->
<script src="js/angularfire.min.js"></script>
</head>
<body ng-app="starter" ng-controller="chatController">
<ion-header-bar class="bar-stable">
<h1 class="title">My Anonymous Chat App</h1>
</ion-header-bar>
<ion-content class="has-subheader">
<div class="row row-bottom">
<div class="col">
<div class="chatbox-container">
<ul class="chatbox">
<!-- We output the messages -->
<li ng-repeat="message in messages">{{messages.content}} </li>
</ul>
</div>
<form name="myform" ng-submit="addMessage(message.theMessage)">
<label class="item item-input message-input">
<!-- the input text field is bound to message.theMessage -->
<input type="text" ng-model="message.theMessage"
placeholder="Type your message..."></input>
</label>
<button class="button button-block button-dark" action="submit"> Send
</button>
</div>
</div>
</ion-content>
</body>
</html>
and my app.js
angular.module('starter', ['ionic', '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) {
StatusBar.styleDefault();
}
});
})
.controller('chatController', ["$scope", "chatMessages", function($scope, chatMessages ) {
//Set messages to chatMessages factory which returns the firebase data
$scope.messages = chatMessages;
//Initialize message object
$scope.message = {};
//Add message to the firebase data
$scope.addMessage = function(message) {
$scope.messages.$add({content: message});
//we reset the text input field to an empty string
$scope.message.theMessage = "";
};
}])
.factory("chatMessages", ['$firebase', "$rootScope", function($firebase, $rootScope){
// create a reference to the Firebase where we will store our data
var ref = new Firebase("https://mattschatapp.firebaseio.com/");
// this uses AngularFire to create the synchronized array
return $firebase(ref.limitToLast(10)).$asArray();
}]);
I'm trying to develop a mobile app with onsen+cordova
What i need is:
When the app start it load login.html page. If the app detect that the user is logged then it redirect to the home.html
For each "protected page" i want to call a function that detected if user is logged.
If not i want to redirect to login page.
All the "protected pages" have a slide menu.
Following what i've done:
index.html
<html ng-app="app2gest">
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height"/>
<title>App2Gest</title>
<link rel="stylesheet" type="text/css" href="vendors/onsen/css/onsenui.css"/>
<link rel="stylesheet" type="text/css" href="vendors/onsen/css/onsen-css-components.css"/>
<!-- Download also your onsen-css-components.css stylesheet using the integrated CSS Components Theme Roller
http://components.onsenui.io -->
<link rel="stylesheet" type="text/css" href="vendors/onsen/css/onsen-css-components-blue-theme.css"/>
<!--<link rel="stylesheet" type="text/css" href="vendors/onsen/css/onsen-css-components-default.css"/>-->
<!--<link rel="stylesheet" type="text/css" href="vendors/onsen/css/onsen-css-components-blue-basic-theme.css"/> -->
<!--<link rel="stylesheet" type="text/css" href="vendors/onsen/css/onsen-css-components-dark-theme.css"/> -->
<!--<link rel="stylesheet" type="text/css" href="vendors/onsen/css/onsen-css-components-sunshine-theme.css"/> -->
<!--<link rel="stylesheet" type="text/css" href="vendors/onsen/css/onsen-css-components-purple-theme.css"/> -->
<link rel="stylesheet" type="text/css" href="css/angular-carousel.css"/>
<!-- NVD3 re-usable charting library (based on D3) -->
<link rel="stylesheet" type="text/css" href="css/nvd3/nv.d3.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<ons-sliding-menu menu-page="menu.html" main-page="login.html" side="left" max-slide-distance="85%" swipable="true" swipe-target-width="100" var="menu">
</ons-sliding-menu>
<!-- Javascripts -->
<script type="text/javascript" src="vendors/onsen/js/angular/angular.js"></script>
<script type="text/javascript" src="js/angular-touch.js"></script>
<script type="text/javascript" src="vendors/onsen/js/onsenui.js"></script>
<script type="text/javascript" src="js/lodash.underscore.min.js"></script>
<script type="text/javascript" src="js/bluebird.js"></script>
<script type="text/javascript" src="js/event.js"></script>
<script type="text/javascript" src="js/angular-local-storage.js"></script>
<script type="text/javascript" src="js/angular-sanitize.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/data.js"></script>
<script type="text/javascript" src="js/app-local-storage.js"></script>
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
home.html
<ons-page ng-controller="HomeController" ng-init="LoginUtility.checkLogin()">
<ons-toolbar fixed-style>
<div class="left">
<ons-toolbar-button onclick="ons.slidingMenu.toggleMenu()">
<ons-icon icon="bars">
</ons-toolbar-button>
</div>
<div class="center">App2Gest</div>
<div class="right">
<ons-toolbar-button onclick="appNavigator.pushPage('settings.html', {title: 'Settings', animation: 'slide'})">
<ons-icon icon="gears">
</ons-toolbar-button>
</div>
</ons-toolbar>
<ons-scroller>
<section class="home-grid">
<div class="grid-menu">
<div class="centering-and-alignment" ng-repeat="row in items| partition:2">
<div class="grid-menu-item list__item list__item--tappable" ng-repeat="item in row" ng-click="showDetail(($parent.$index * row.length) + $index);">
<ons-icon icon="{{item.icon}}"></ons-icon>
<div class="grid-menu-item-label">{{item.title}}</div>
</div>
</div>
</div>
</section>
</ons-scroller>
<div>
</div>
</ons-page>
login.html
<ons-navigator title="Navigator" var="appNavigator">
<ons-page sliding-menu-ignore="true" ng-controller="LoginController" ng-init="LoginUtility.checkLogin()">
<ons-toolbar>
<div class="left">
</div>
<div class="center">App2Gest - Login</div>
</ons-toolbar>
<div class="main-image-wrapper">
<i class="fa fa-sign-in main-image"></i>
</div>
<form ng-submit="LoginUtility.login()">
<input type="email" class="text-input--underbar" placeholder="Username" value="" ng-model="username">
<input type="password" class="text-input--underbar" placeholder="Password" value="" ng-model="password">
<br>
<button class="button login-button">Log in</button>
<br>
</form>
</ons-page>
</ons-navigator>
app.js
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
ons.setDefaultDeviceBackButtonListener(function() {
if (navigator.notification.confirm("Vuoi chiudere l\'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
}
))
;
});
// Open any external link with InAppBrowser Plugin
$(document).on('click', 'a[href^=http], a[href^=https]', function(e) {
e.preventDefault();
var $this = $(this);
var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), target);
});
// Initialize Push Notifications
// Uncomment the following initialization when you have made the appropriate configuration for iOS - http://goo.gl/YKQL8k and for Android - http://goo.gl/SPGWDJ
//app.initPushwoosh();
},
// Update DOM on a Received Event
receivedEvent: function(id) {
//var parentElement = document.getElementById(id);
//var listeningElement = parentElement.querySelector('.listening');
//var receivedElement = parentElement.querySelector('.received');
//listeningElement.setAttribute('style', 'display:none;');
//receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
// Register device for Push Notifications
initPushwoosh: function() {
var pushNotification = window.plugins.pushNotification;
if (device.platform == "Android") {
registerPushwooshAndroid();
}
if (device.platform == "iPhone" || device.platform == "iOS") {
registerPushwooshIOS();
}
}
};
(function() {
var app = angular.module('app2gest', ['onsen.directives', 'ngTouch', 'ngSanitize', 'appLocalStorage', 'LocalStorageModule', 'ui.event']);
app.controller("LoginController", function($scope, LoginUtility) {
$scope.LoginUtility = LoginUtility;
$scope.LoginUtility.setScope($scope);
});
// Home Controller
app.controller('HomeController', function($scope, Data, LoginUtility) {
$scope.items = Data.items;
$scope.LoginUtility = LoginUtility;
$scope.LoginUtility.setScope($scope);
$scope.showDetail = function(index) {
var selectedItem = $scope.items[index];
Data.selectedItem = selectedItem;
if (selectedItem.type === 'internal') {
$scope.ons.navigator.pushPage(selectedItem.url, {title: selectedItem.title, animation: 'slide'});
}
else {
window.open(selectedItem.url);
}
};
});
app.controller('CaricoHomeController', function($scope) {
});
// Menu Controller
app.controller('MenuController', function($scope, MenuData) {
$scope.items = MenuData.items;
$scope.showDetail = function(index) {
var selectedItem = $scope.items[index];
MenuData.selectedItem = selectedItem;
$scope.ons.slidingMenu.setMainPage(selectedItem.page, {closeMenu: true});
};
});
// Barcodescanner Controller
app.controller('BarcodescannerController', function($scope) {
$scope.scan = function() {
cordova.plugins.barcodeScanner.scan(function(result) {
$scope.result = result;
$scope.$apply();
}, function(error) {
$scope.error = error;
$scope.$apply();
});
}
});
//dummy implementation
app.factory('LoginUtility', function() {
var username;
var password;
var scopeVar;
var loginObj = {};
loginObj.setScope = function(elem) {
scopeVar = elem;
};
loginObj.isGuest = function() {
return username == null;
};
loginObj.login = function() {
console.log('login called');
username = scopeVar.username;
password = scopeVar.password;
//dummy login, we assume login always succeded
scopeVar.ons.slidingMenu.setMainPage("home.html", {closeMenu: true});
};
loginObj.logout = function() {
username = null;
};
loginObj.checkLogin = function() {
if (this.isGuest() && **imNotInLoginPage()**) {
scopeVar.ons.slidingMenu.setMainPage("login.html", {closeMenu: true});
}
};
return loginObj;
});
// Filter
app.filter('partition', function($cacheFactory) {
var arrayCache = $cacheFactory('partition');
var filter = function(arr, size) {
if (!arr) {
return;
}
var newArr = [];
for (var i = 0; i < arr.length; i += size) {
newArr.push(arr.slice(i, i + size));
}
var cachedParts;
var arrString = JSON.stringify(arr);
cachedParts = arrayCache.get(arrString + size);
if (JSON.stringify(cachedParts) === JSON.stringify(newArr)) {
return cachedParts;
}
arrayCache.put(arrString + size, newArr);
return newArr;
};
return filter;
});
})();
For the dummy function imNotInLoginPage() at the start of the app if use appNavigator.getCurrentPage() it works but appNavigator.getCurrentPage().page is empty
After Login instead if i call appNavigator.getCurrentPage() it is undefined and i receive a js undefined error.
How can i check if i'm in loginpage or in another?
And the very big question, is this a good praticse in angular?
Otherwise how can i achieve this goal with angular+onsen???
The support from the onsen's theme is very poor.
I've found other solutions involving angular route, but there are not compatible with onsen.
I'm going crazy for implementing this standard thing. I hope that someone can help me, providing a complete example code.
Thank you
I created sample. If I misunderstand what you mean, please tell me.
index.html
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<script src="components/loader.js"></script>
<link rel="stylesheet" href="components/loader.css">
<link rel="stylesheet" href="css/style.css">
<script src="js/app.js"></script>
</head>
<body>
<ons-navigator var="myNavigator" page="login.html">
</ons-navigator>
</body>
</html>
app.js
var myApp = angular.module("myApp", ['onsen']);
myApp.controller('loginCtrl', function($scope) {
if(checkLogin()) {
openProtectedPage();
}
function openProtectedPage() {
alert("you are already logged in. open protected page");
setTimeout(function() {
myNavigator.pushPage('protected.html');
}, 1000);
}
function checkLogin() {
//temporariry return true;
// please write your own logic to detect user login;
return true;
}
});
login.html
<ons-page ng-controller="loginCtrl">
<ons-toolbar>
<div class="center">Login Page</div>
</ons-toolbar>
<div style="text-align: center; margin-top: 30px;">
Email: <input type="text" />
</div>
<div style="text-align: center; margin-top: 30px;">
Password: <input type="text" />
</div>
<div style="text-align: center;margin-top: 30px;">
<ons-button>
Sign In
</ons-button>
</div>
</ons-page>
protected.html
<ons-page>
<ons-sliding-menu var="app.slidingMenu" menu-page="menu.html" main-page="page1.html" side="left" type="overlay" max-slide-distance="200px">
</ons-sliding-menu>
</ons-page>
I hope this example would help you.
$modal doesn't appear with internal html files.
When I click on "add", The grey window appears but without the internal html content.
I tried to place an external url like "http://www.google.com" and it worked!.
I placed for sure the file under partials/dialog.html.
I'm using Ionic framework.
The index.html:
<!DOCTYPE html>
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Todo List App</title>
<!-- ionic css -->
<link href="lib/css/ionic.css" rel="stylesheet">
<!-- Bootstrap css -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- ionic/angularjs scripts -->
<script src="lib/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!--Angular-UI bootstrap script -->
<script src="js/ui-bootstrap-tpls-0.10.0.min.js"></script>
<!-- your app's script -->
<script src="js/angular-local-storage.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="MyCtrl">
<header class="bar bar-header bar-positive">
<div class="buttons">
<button class="button button-icon icon ion-ios7-minus-outline" ng-click="showDelete = !showDelete"></button>
</div>
<h1 class="title">Todo List</h1>
<button class="button button-icon icon ion-ios7-bolt" ng-click="clearItems()"></button>
<button class="button button-icon icon ion-ios7-plus-outline" ng-click="addItem()"></button>
</header>
<ion-content class="has-header">
<ion-list show-delete="showDelete"
on-delete="onItemDelete(item)"
option-buttons="itemButtons">
<ion-item ng-repeat="item in items"
item="item"
href="#/item/{{item.id}}">
Item {{ item.id}}
</ion-item>
</ion-list>
</ion-content>
</body>
<!--</html>-->
The app.js:
var myApp = angular.module('ionicApp', ['ionic', 'LocalStorageModule', 'ui.bootstrap']);
myApp.controller('MyCtrl', function($scope, $modal, localStorageService) {
$scope.items = [{id: 1}];
$scope.itemButtons = [
{
text: 'Edit',
type: 'button-assertive',
onTap: function(item) {
alert('Edit Item: ' + item.id);
}
},
{
text: 'Share',
type: 'button-calm',
onTap: function(item) {
alert('Share Item: ' + item.id);
}
}
];
$scope.onItemDelete = function(item) {
if (localStorageService.get('hey'))
{
var values = new Array();
values = localStorageService.get('hey');
var indexMy = values.indexOf(item);
values.splice(indexMy, 1);
localStorageService.add('hey', values);
}
//Remove the item from the GUI
$scope.items.splice($scope.items.indexOf(item), 1);
};
$scope.reloadItem = function() {
var values = new Array();
if (localStorageService.get('hey'))
{
values = localStorageService.get('hey');
var index;
for (index = 0; index < values.length; index++) {
$scope.items.push({id: values[index]});
}
}
};
$scope.clearItems = function() {
localStorageService.clearAll();
$scope.items = [];
};
$scope.reloadItem();
$scope.addItem = function() {
//Test - should be remove on release date
$scope.items.push({id : "sharon"});
var modalInstance = $modal.open({
templateUrl: 'partials/dialog.html',
controller: ModalInstanceCtrl
});
modalInstance.result.then(
function(newItemInput) {
var values = new Array();
if (localStorageService.get('hey'))
{
values = localStorageService.get('hey');
}
values.push(newItemInput);
//$scope.items.push({id : values[0]});
localStorageService.add('hey', values);
},
function() {
//$scope.lol = "no";
});
};
});
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.newItemObject = {};
$scope.ok = function() {
$modalInstance.close($scope.newItemObject.newItemInput);
};
$scope.cancel = function() {
$modalInstance.dismiss();
};
};
The internal html "dialog.html":
<html>
<head>
<title>title</title>
</head>
<body>
<div>
<p>Enter your new item</p>
<!-- <p><input type="text" ng-model="newItemObject.newItemInput" class="form-control" placeholder="Text input">{{newItemInput}}</p> -->
<p><button>OK</button>
<button>Cancel</button></p>
</div>
</body>
</html>
I have had issues with bootstraps css interfering with ionic modals, try commenting out css/bootstrap.min.css and see if it makes any difference.