Angular js routing not loading after using yeoman generator - angularjs

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>

Related

Ionic Framework Edit functionality not working

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

google map application passing latitude and longitude so that the user can then navigate to the place

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;
}

Howto access the passed variable in a custom directive with JavaScript?

I have made a custom directive and can access the passed variable in the direct.template within double squiqqly brackets like this directive.template = '<input/>{{text.incorrectAnswers}}' but how do I access it in JavaScript so I can change it and then pass it back into my directive.template?
<html ng-app="mainApp">
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-controller="mainController" style="padding: 20px 0">
<div class="col-xs-8">
<div class="panel panel-default">
<div class="panel-heading">Company Info</div>
<div class="panel-body">
<div ng-repeat="text in texts">
<div data-show-phrase data-text="text"></div>
</div>
</div>
</div>
</div>
<script>
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', function ($scope) {
$scope.texts = [
{
body: 'Customer 1 is from [##blank] and Customer 2 is from [##blank].',
correctAnswers: 'Berlin;Hamburg',
incorrectAnswers: 'Stuttgart;Munich;Frankfurt'
},
{
body: 'Company 3 is located in [##blank].',
answers: 'Bremen',
incorrectAnswers: 'Hannover;Dresden;Stuttgart'
}
];
});
mainApp.directive('showPhrase', function () {
var directive = {};
directive.restrict = 'A';
directive.scope = {
text: '=text'
};
//var parts = incorrectAnswers.split(';'); //Error: incorrectAnswers is not defined
//var parts = $scope.incorrectAnswers.split(';'); //Error: incorrectAnswers is not defined
var parts = directive.incorrectAnswers.split(';'); //Error: incorrectAnswers is not defined
directive.template = '<input/>{{text.body}}';
return directive;
});
</script>
</body>
</html>
2-way bound properties available as a part of the scope object and that cannot be accessed during the creation of a directive, because no scope exists yet. You need to at least wait till linking phase or in the controller to access the scope and its properties. If you are using controllerAs syntax (with 1.3.x) then you would turn on bindToController:true to be able to access it as properties of the controller instance. And as long as you use bindings in your template, angular will take care of updating the template for dynamic changes in the bound properties.
Example:-
mainApp.directive('showPhrase', function() {
var directive = {};
directive.restrict = 'A';
directive.scope = {
text: '='
};
/*Linking function*/
directive.link = function(scope, elm) {
scope.parts = scope.text.incorrectAnswers.split(';');
console.log(parts)
}
directive.template = '<div><input/>{{text.body}} <ul><li ng-repeat="part in parts">{{part}}</li></ul></div>';
return directive;
});
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', function($scope) {
$scope.texts = [{
body: 'Customer 1 is from [##blank] and Customer 2 is from [##blank].',
correctAnswers: 'Berlin;Hamburg',
incorrectAnswers: 'Stuttgart;Munich;Frankfurt'
}, {
body: 'Company 3 is located in [##blank].',
answers: 'Bremen',
incorrectAnswers: 'Hannover;Dresden;Stuttgart'
}];
});
mainApp.directive('showPhrase', function() {
var directive = {};
directive.restrict = 'A';
directive.scope = {
text: '='
};
directive.link = function(scope, elm) {
scope.parts = scope.text.incorrectAnswers.split(';');
console.log(parts)
}
directive.template = '<div><input/>{{text.body}} <ul><li ng-repeat="part in parts">{{part}}</li></ul></div>';
return directive;
});
<html ng-app="mainApp">
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-controller="mainController" style="padding: 20px 0">
<div class="col-xs-8">
<div class="panel panel-default">
<div class="panel-heading">Company Info</div>
<div class="panel-body">
<div ng-repeat="text in texts">
<div data-show-phrase data-text="text"></div>
</div>
</div>
</div>
</div>
<script>
</script>
</body>
</html>

OnsenUi Angular and Login

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

$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.

Resources