$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.
Related
I have a simple model with a list of names and corresponding images. I'm trying to click on the name of the image and load the corresponding image. I can't get the image to load. The list of names appears on the page, but when I click them nothing happens. Please help with code. Thx!
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<meta charset="UTF-8">
<title>Cat Clicker</title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel ="stylesheet" type "text/css" href ="clicker.css">
<script type = "text/javascript" src="Libs/angular.js"></script>
<script type = "text/javascript" src="js/CatClickerMe.js"></script>
<body>
<div ng-controller = "MainController">
<div ng-repeat = "cat in options.catList">
<h3 ng-click = "MainController.selectCat($index)">{{cat.name}}</h3>
<h3>{{MainController.selectedCat.name}}</h3>
<img ng-src = "{{MainController.selectedCat.images}}" >
</div>
</div>
</div>
</body>
</html>
JS
(function() {
"use strict";
angular.module('myApp',[]);
angular.module('myApp').controller('MainController', function($scope) {
var vm = this;
$scope.options = {
catList:[
{
name: 'Fluffy',
images: 'images/Fluffy.jpeg'
},
{
name: 'Tabby',
images: 'images/tabby.jpeg'
}
],
};
vm.selectCat=function(pos) {
vm.selectedCat = angular.copy(vm.catList[pos]);
vm.selectedCat.pos = pos;
};
activate();
function activate() {
}
})
})();
You are mixing up $ scope and vm, go with one approach. You need to use controller as syntax in the template,
<div ng-controller = "MainController as vm">
DEMO
(function() {
"use strict";
angular.module('myApp',[]);
angular.module('myApp').controller('MainController', function($scope) {
var vm = this;
vm.selectCat = selectCat;
this.options = {
catList:[
{
name: 'Fluffy',
images: 'images/Fluffy.jpeg'
},
{
name: 'Tabby',
images: 'images/tabby.jpeg'
}
],
};
function selectCat(pos) {
vm.selectedCat = pos;
};
})
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<meta charset="UTF-8">
<title>Cat Clicker</title>
<body>
<div ng-controller = "MainController as vm">
<div ng-repeat = "cat in vm.options.catList">
<h3 ng-click = "vm.selectCat(cat)">{{cat.name}}</h3>
<h3>{{vm.selectedCat.name}}</h3>
<img ng-src = "{{vm.selectedCat.images}}" >
</div>
</div>
</div>
</body>
</html>
I've used yeoman generator to generat my app and i've decided to copy my app in a clean folder but seams that the rounting is not working as expected, the templates ain't loading at all
My app js
'use strict';
angular
.module('angularJsApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'main',
controllerAs: 'mainController'
})
.when('/users', {
templateUrl: 'views/users.html',
controller: 'main',
controllerAs: 'mainController'
})
.when('/active_users', {
templateUrl: 'views/active_users.html',
controller: 'second',
controllerAs: 'secondController'
})
.otherwise({
redirectTo: '/'
});
});
Controllers
'use strict';
// users factory
angular.module('angularJsApp').factory("myFactory", function() {
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
var persoane = existingEntries;
var factory = {};
factory.getPersons = function() {
return {
existingEntries: existingEntries,
persoane: persoane
};
}
return factory;
});
// modules
angular.module('angularJsApp').controller('main', function($scope, myFactory) {
var dataMain = this;
$scope.adaugaperson = function() {
var name = $scope.newName;
var lastname = $scope.newLastName;
var tel = $scope.newPhone;
var email = $scope.newEmail;
var age = $scope.newAge;
var gender = $scope.newGender;
var entry = {
"name": name,
"lastname": lastname,
"tel": tel,
"email": email,
"age": age,
"gender": gender,
"isChecked": false
};
// sf not having any entry, crate
if ($scope.existingEntries == null) $scope.existingEntries = [];
localStorage.setItem("entry", JSON.stringify(entry));
// save allEntries back to local storage
$scope.existingEntries.push(entry);
localStorage.setItem("allEntries", JSON.stringify($scope.existingEntries));
// reset the form
$scope.newName = '';
$scope.newLastName = '';
$scope.newPhone = '';
$scope.newEmail = '';
$scope.newAge = '';
$scope.newGender = '';
};
// get persons
initPersons();
function initPersons() {
$scope.persoane = myFactory.getPersons().persoane;
$scope.existingEntries = myFactory.getPersons().existingEntries;
}
// remove person
$scope.remove = function(indexNumber) {
$scope.existingEntries.splice(indexNumber, 1);
localStorage.setItem("allEntries", JSON.stringify($scope.existingEntries));
}
// var for index targeting
var indexValue = undefined;
// populate form
$scope.populate = function(indexNumber) {
indexValue = indexNumber;
$scope.newName = $scope.existingEntries[indexNumber]["name"]
$scope.newLastName = $scope.existingEntries[indexNumber]["lastname"];
$scope.newPhone = $scope.existingEntries[indexNumber]["tel"];
$scope.newEmail = $scope.existingEntries[indexNumber]["email"];
$scope.newAge = $scope.existingEntries[indexNumber]["age"];
$scope.newGender = $scope.existingEntries[indexNumber]["gender"];
}
// save edited user
$scope.editUser = function(indexNumber) {
indexNumber = indexValue;
$scope.existingEntries[indexValue]["name"] = $scope.newName;
$scope.existingEntries[indexValue]["lastname"] = $scope.newLastName;;
$scope.existingEntries[indexValue]["tel"] = $scope.newPhone;
$scope.existingEntries[indexValue]["email"] = $scope.newEmail;
$scope.existingEntries[indexValue]["age"] = $scope.newAge
$scope.existingEntries[indexValue]["gender"] = $scope.newGender;
$scope.newName = "";
$scope.newLastName = "";
$scope.newPhone = "";
$scope.newEmail = "";
$scope.newAge = "";
$scope.newGender = "";
localStorage.setItem("allEntries", JSON.stringify($scope.existingEntries));
}
// active users state
$scope.activeUsers = function(indexNumber) {
indexValue = indexNumber;
$scope.boolVal = $scope.existingEntries[indexNumber]["isChecked"];
if ($scope.boolVal === false) {
$scope.existingEntries[indexNumber]["isChecked"] = true;
} else {
$scope.existingEntries[indexNumber]["isChecked"] = false;
}
localStorage.setItem("allEntries", JSON.stringify($scope.existingEntries));
}
});
// controler for users active
angular.module('angularJsApp').controller('second', function($scope, myFactory) {
init();
function init() {
$scope.persoane = myFactory.getPersons().persoane;
$scope.existingEntries = myFactory.getPersons().existingEntries;
}
});
HTML
<!doctype html>
<html xmlns:ng="http://angularjs.org" ng-app>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.css" />
<!-- endbower -->
<!-- endbuild -->
<!-- build:css(.tmp) styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
</head>
<body ng-app="angularJsApp">
<!--[if lte IE 8]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="header">
<div class="navbar navbar-default" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#js-navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#/">angularJs</a>
</div>
<div class="collapse navbar-collapse" id="js-navbar-collapse">
<ul class="nav navbar-nav">
<li>Home</li>
<li><a ng-href="#!/active_users">Active Users</a></li>
<li><a ng-href="#!/users/">Users</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container">
<div ng-view>
</div>
</div>
<div class="footer">
<div class="container">
</div>
</div>
<!-- build:js(.) scripts/vendor.js -->
<!-- bower:js -->
<script src="components/jquery/dist/jquery.js"></script>
<script src="components/angular/angular.js"></script>
<script src="components/bootstrap/dist/js/bootstrap.js"></script>
<!-- endbower -->
<!-- endbuild -->
<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<!-- endbuild -->
</body>
</html>
Remove ng-app directive from your html tag which has no module specified, apparently it isn't allowing your ng-app="angularJsApp" placed on body tag.
From Docs
Only one AngularJS application can be auto-bootstrapped per HTML
document. The first ngApp found in the document will be used to define
the root element to auto-bootstrap as an application.
Also you have to add angular-route.js right after angular.js
<script src="components/angular/angular.js"></script>
<script src="components/angular/angular-route.js"></script>
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
I'm pretty new to Ionic and AngularJS. I tried to create a note app but my controllers.js did not seem to understand services.js. What do I have to do to fix this problem. Thanks in advance.
And this is my code look like
app.js
(function() {
var app = angular.module('starter', ['ionic', 'starter.controllers' ,'starter.services'])
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('list', {
url: '/list',
templateUrl : 'templates/list.html'
});
$stateProvider.state('edit', {
url: '/edit/:Id',
templateUrl : 'templates/edit.html',
controller : 'EditCtrl'
});
$stateProvider.state('add', {
url: '/add',
templateUrl : 'templates/edit.html',
controller : 'AddCtrl'
});
$urlRouterProvider.otherwise('/list');
});
app.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();
}
});
})
}());
controllers.js
angular.module('starter.controllers', [])
.controller('ListCtrl', function($scope, NoteStore) {
$scope.notes = NoteStore.list();
});
.controller('EditCtrl', function($scope, $state, NoteStore) {
$scope.title = "Edit";
$scope.note = angular.copy(NoteStore.get($state.params.Id));
$scope.save = function() {
NoteStore.update($scope.note);
$state.go('list')
};
});
.controller('AddCtrl', function($scope, $state, NoteStore) {
$scope.title = "New Note";
$scope.note = {
id: new Date().getTime().toString()
};
$scope.save = function() {
NoteStore.create($scope.note);
$state.go('list')
};
});
services.js
angular.module('starter.services', [])
.factory('NoteStore', function() {
var notes = [];
return {
list : function() {
return notes;
},
get : function(noteId) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].id === noteId) {
return notes[i];
}
}
return undefined;
},
create : function(note) {
notes.push(note);
},
update : function(note) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].id === note.id) {
notes[i] = note;
return;
}
}
return undefined;
}
}
});
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">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-nav-bar class="bar-assertive">
<ion-nav-back-button class="button-clear">
<i class="ion-arrow-left-c"></i> Back
</ion-nav-back-button>
</ion-header-bar>
<ion-nav-view>
</ion-nav-view>
</ion-pane>
</body>
</html>
list.html
<ion-view view-title="My Notes">
<ion-nav-buttons side="right">
</ion-nav-buttons>
<ion-content ng-controller="ListCtrl">
<div class = "list">
<a href="#/edit/{{note.id}}" class = "item" ng-repeat = "note in notes">
<h2>{{note.title}}</h2>
<p>{{note.description}}</p>
</a>
</div>
</ion-content>
</ion-view>
edit.html
<ion-view view-title="{{title}}">
<ion-content>
<div class="list card">
<div class="item item-input">
<input type="text" placeholder="Title" ng-model="note.title">
</div>
<div class="item item-input">
<textarea rows="5" placeholder="Description" ng-model="note.description"></textarea>
</div>
</div>
<div class="padding">
<button class="button button-positive button-block" ng-click="save()">Save</button>
</div>
</ion-content>
</ion-view>
When you separate it into separate files first make sure you load the files in your index.html
so for each controller or service js file you will need in your index.html
<script type="text/javascript" src="//path to js file"></script>
The next thing you need to do is inject your services and your controller into your main app.module which you did do here:
var app = angular.module('starter', ['ionic', 'starter.controllers' ,'starter.services'])
You also need to inject your service into you controller which you did not do so in
angular.module('starter.controllers', [])
you need to inject 'stater.services'
so it should look like
angular.module('starter.controllers', ['starter.services'])
then in your controller you can inject whatever factory you need
.controller('EditCtrl', function(NoteStore){})
each module needs to have the other modules it depends on injected into it.
For example on my app i also inject ionic into my controllers and services.
That should get it working for you. If you want me to post more examples let me know.
Found the problem!!!
In the controllers.js you can't end a controller and start another.
If you want to use multiple controllers on the same JS file, you have to use semicolon only on the last controller.
I.E. You have 3 controllers
.controller('ListCtrl', function(){})
.controller('EditCtrl', function(){})
.controller('AddCtrl', function(){});
Only the last controller have to end with semicolon.
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.