Navigate to new page in Ionic-V1 - javascript

I'm currently working on a project using Ionic v1. I have multiple user type in the project, wherein every user type must be redirected to a different page based on their time. I am unable to achieve this. Here is my code:
app.js:
.state('tab.login', {
url: '/login',
views: {
'tab-login': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl'
}
}
})
.state('guest.home' , {
url: '/guesthome',
views: {
'guest-home': {
templateUrl: 'templates/guest-home.html',
controller: 'GuestCtrl'
}
}
})
.state('agent.home' , {
url: '/agenthome',
views: {
'agent-home': {
templateUrl: 'templates/agent-home.html',
controller: 'AgentCtrl'
}
}
})
controller.js:
.controller('LoginCtrl', function($scope, $state) {
$scope.userLogin = function(email, password) {
Backendless.UserService.login( $scope.email, $scope.password, true )
.then( $scope.userLoggedIn )
.catch ( $scope.gotError )
}
$scope.userLoggedIn = function( user ) {
console.log("User has logged in");
if ( user.user_type === "g" )
$state.go('guest.home');
else
$state.go('agent.home');
}
$scope.gotError = function( err ) {
console.log( "error message - " + err.message );
console.log( "error code - " + err.statusCode );
}
})
tabs-login.html:
<ion-content class="padding" ng-controller="LoginCtrl">
<div class="list">
<label class="item item-input item-floating-label">
<span class="input-label">Email</span>
<input type="text" placeholder="Email" ng-model="email">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Password</span>
<input type="password" placeholder="Password" ng-model="password">
</label>
</div>
<div class="text-center">
<button class="button button-positive" ng-click="userLogin()">
Login
</button>
</div>
</ion-content>
I'm getting the error error message - Could not resolve 'guest.home' from state 'tab.login' What am I doing wrong?

I believe the problem might be related to the fact that you use dots on your state names, without defining an abstract state to hold children.
Give it a shot without the dots ('guesthome' maybe?), or change your routing to have abstract states.
Here's an example:
$stateProvider
.state('setup', {
url: '/setup',
abstract: true,
templateUrl: 'js/views/setupView.html',
controller: 'SetupController'
})
.state('setup.bluetooth', {
url: '/bluetooth',
views: {
'setupContent': {
templateUrl: 'js/views/bluetoothSetupView.html',
controller: 'BluetoothSetupController'
}
}
})
.state('setup.truck', {
url: '/truck',
views: {
'setupContent': {
templateUrl: 'js/views/truckSetupView.html',
controller: 'TruckSetupController'
}
}
})

Related

angular-route wont redirect

I have a problem, my page after login is not redirecting to main page. I have checked condition login working when I use $window.location. I want to use angular-route to prevent user without login to access my main menu. If I use $window.location, the user can access my main menu without login. Here is my js file
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'index.html'
})
.when('/mainmenu',{
resolve:{
"check":function($location,$rootScope){
if (!$rootScope.loggedIn) {
$location.path('/');
}
}
},
templateUrl:'content/mainmenu2.html'
})
.otherwise({
redirectTo:'/'
});
});
app.controller("logincont", ['$scope','$http','$window','$rootScope','$location',function($scope,$http,$window,$rootScope,$location){
$scope.login = function () {
$http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
$scope.reslogin = response.data;
if($scope.reslogin == null)
{
alert('Login Incorrect');
}
else
{
$rootScope.loggedIn = true;
$location.path('/mainmenu');
}
});
};
}]);
here is my html
<form>
<h1 class="tengah"> Form Login </h1>
<div class="form-group">
<label for="inputId">User Id</label>
<input type="text" class="form-control" ng-model="userid" placeholder="userid" required>
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" ng-model="pass" placeholder="Password" required>{{password}}
</div>
<button type="submit" class="btn btn-primary" ng-click="login()">
<span class="fa fa-sign-out"></span>Login</button>
</form>
You can do it by using a flag allowUnauth on the routes those you don't want to authenticate for e.g login and then change your routing like:-
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'index.html',
allowUnauth:true
})
.when('/mainmenu',{
templateUrl:'content/mainmenu2.html'
}).otherwise({
redirectTo:'/'
});
});
var unauthRoutes= [];
angular.forEach($route.routes, function(route, path) {
// push route onto unauthRoutes if it has a truthy allowUnauth value
route.allowUnauth && (unauthRoutes.push(path));
});
$rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc)
{
var atuhRoute= (-1 === unauthRoutes.indexOf($location.path()));
if(atuhRoute && !$rootScope.loggedIn) {
$location.path('/');
}
});
Working plunker
Try something like
"use strict";
configureApp.$inject = ['$routeProvider'];
function configureApp($routeProvider) {
$routeProvider
.when('/mainmenu', {
resolve: {
ensureAthenticated: (function() {
ensureAthenticated.$inject = ['$rootScope'];
function ensureAthenticated($rootScope) {
if(!$rootScope.loggedIn) {
return Promise.reject('not athenticated');
}
else return Promise.resolve();
};
return ensureAthenticated;
}())
},
templateUrl:'content/mainmenu2.html'
})
.otherwise('/');
}
app.config(configureApp);

Ng-View is not give the output "RangeError: Maximum call stack size exceeded"

Ng-View is not give the output . Trying to route form one page to another by page instead i getting this error .
"RangeError: Maximum call stack size exceeded"
Kindly check the following and give your suggestion to overcome that .
App.jss
'use strict';
var app = angular.module('Sab', ['ui.filters','ui','ngRoute'])
.config(["$routeProvider", function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'index.html',
controller: 'menuCtrl'
}).
when('/Deals/:offer_name', {
templateUrl: 'Deals.html',
controller: 'abCtrl'
}).
when('/D', {
templateUrl: 'D.html',
}).
otherwise({
redirectTo: '/home'
});
}])
.controller('menuCtrl', function($scope,$http) {
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.myData = response.data;
$scope.offerName = ''; //set initially
$scope.selectedIndex = -1;
$scope.filteredOffers = [];
});
$scope.showData = function(offer_name, index) {
$scope.offerName = offer_name;
$scope.filteredOffers = $scope.myData.filter(function(offer) {
return offer.offer_name == $scope.offerName;
});
$scope.selectedIndex = index;
}
})
.controller('abCtrl',function($scope,$http,$stateParams,$filter,$window) {
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
var offerName = $stateParams.offer_name;
$scope.filteredOffers = $filter('filter')(response.data, {offer_name: offerName});
// $scope.filteredOffers = _.filter(response.data, ["offer_name",offerName]);
console.log($scope.filteredOffers)
console.log(offerName)
$scope.dealopen = function($a){
for (var i=0;i<response.data.length;i++)
{
//console.log($scope.data[i].name);
$link=response.data[i].link;
if ($link==$a)
{
$window.open($link,"_self","location=yes");
console.log($a);
}
}
}
});
});
Html
<div class="row" ng-app="Sab" ng-controller="menuCtrl" >
<ng-view></ng-view>
<div class="col col-100 " ng-repeat="da in myData | unique: 'store_image'" >
<div class="card col " >
<img class=" img-responsive " ng-src="{{ da.store_image}}"
ng-click="showData(da.offer_name, $index)"
/>
<div class="caption">
<a class="item item-text-wrap" href="#/Deals/{{da.offer_name }}" ng-click="showData(da.offer_name, $index)"
>
<b class="group inner list-group-item-heading center-block">
{{da.category }} Deals </b>
</a>
</div>
</div>
</div>
</div>
</div>
First, which comes to mind - infinite recursion. First of all, your menuCtrl is loaded two times:
In html
ng-controller="menuCtrl"
In route
when('/home', {
templateUrl: 'index.html',
controller: 'menuCtrl'
})
Let's start from fixing this. The next depends, I think on your other html templates.

new state inside chat details state (ionic tabs)

I try to create an ionic app which contains tabs
this is my tabs
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
}
})
.state('tab.chats', {
url: '/chats',
views: {
'tab-chats': {
templateUrl: 'templates/tab-chats.html',
controller: 'ChatsCtrl'
}
}
})
.state('tab.chat-detail', {
url: '/chats/:chatId',
views: {
'tab-chats': {
templateUrl: 'templates/chat-detail.html',
controller: 'ChatDetailCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');
});
inside the chat detail tab , I have button ( student list) should take me to another view and keep me inside the chat tab
so , how to do this ?
this is chat detail page
<ion-view view-title="{{chat.name}}">
<ion-content class="padding">
<img ng-src="{{chat.face}}" style="width: 64px; height: 64px">
<p>
{{chat.name}}
</p>
<p>
{{chat.instructor}}
</p>
<ion-toggle ng-model="chat.availabe">
Available
</ion-toggle>
<a class="button button-block button-royal">
List Student
</a>
</ion-content>
</ion-view>
I highly recommend you checking out the directives already built into ionic v1 https://ionicframework.com/docs/api/directive/ionTabs/
In your html
<button class="button button-block button-royal" ng-click="changeState()">
List Student
</button>
Then in your associated controller (I believe its ChatDetailCtrl, dont forget to inject $state)
$scope.changeState = function() {
$state.go('tab.example'); //
};
app.js
.state('tab.example', {
url: '/example',
views: {
'tab-chats': {
templateUrl: 'templates/example.html',
controller: 'ChatDetailCtrl'
}
}
})

Error: [ng:areq] Argument 'AuthCtrl' is not a function, got undefined

This issue has been posted a few times but I cannot seem to find the error within my code. Can somebody help spot the issue in my code?
Below is my app.js file
'use strict';
/**
*jslint node:true
* #ngdoc overview
* #name impApp
* #description
* # impApp
*
* Main module of the application.
*/
/*global Firebase, angular*/
angular
.module('impApp', [
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'firebase'
])
.config(function ($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/', {
templateUrl: 'views/login.html',
controller: 'AuthCtrl',
controllerAs: 'auth'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.otherwise({
redirectTo: '/'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Secondly, this is my controller contents on "auth.js":
'use strict';
/*global Firebase, angular, console*/
angular.module('impApp')
// Re-usable factory that generates the $firebaseAuth instance
.factory("Auth", function ($firebaseAuth) {
var ref = new Firebase("https://impl.firebaseio.com");
return $firebaseAuth(ref);
})
.controller('AuthCtrl', function ($scope, $http, Auth) {
// Listens for changes in authentication state
Auth.$onAuth(function (authData) {
$scope.authData = authData;
});
// Logs in a user with email & password
$scope.login = function () {
Auth.authWithPassword({
email : $scope.email,
password : $scope.password
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
};
// Logs out the logged-in user
$scope.logout = function () {
Auth.$unauth();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Finally, I have outlined the "login.html" contents:
<div>
<form class="form-signin">
<h2 class="form-signin-heading">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
<p></p>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Thank you Pierre-Alexandre. Adding the link to the js file in the index.html resolved this issue.

UI-Router $stateParams With Master Detail Pattern

I need a Master Detais pattern for my web site. In index lots of thumbnails and every thumbnail link to their detailed page. I make a progress but does not get to work. Its load thumbnails on index oage but when I click to thumbnails its load blank page.
Index:
<body ui-view="viewA">
<div class="row" ui-view="viewB">
<div class="col s12 m6 l4" ng-repeat = "manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="icerikDetails({id:manga.id})" class="thumbnail">
<img src="/kapaklar/{{manga.kapak}}">
</a>
JS:
angular.module('nasuh',["ui.router"])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('index', {
url: "/",
views: {
"viewA": { templateUrl: "index.html",
controller: "indexCtrl",}
}})
$stateProvider
.state('icerik', {
url: "/icerik",
views: {
"viewB": { templateUrl: "icerik.html",
controller: "mmgCtrl",},
}})
$stateProvider
.state('icerikDetails', {
url: "/icerik/:id",
template: "<div>{{details }}</div>",
controller: "mmgCtrl",
resolve: {
getData : function(MY, $stateParams, $filter){
return MY.isimler.then(function(res){
return $filter('filter')(res.data, {id: $stateParams.id}, true)[0];
});}
}
})
$urlRouterProvider.otherwise("/");
})
factory and controllers:
.factory('MY', function($http){
var factory = {};
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
factory.isimler = $http.get(url);
return factory;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen){
$scope.mangas = alHemen;
});
})
.controller('mmgCtrl', function($scope, getData) {
$scope.manga = getData.then(function(data){
$scope.details = data;
});})
I am not sure what you are trying to achieve, but at least I tried to convert your snippets into something working.
There is a working example
To get more understanding, do read these:
Nested States and Nested Views
Multiple Named Views
These are states, with a hiererchy. Index is super root, and details is super child:
$stateProvider
.state('index', {
url: "/",
views: {
"": {
templateUrl: "index.tpl.html",
controller: "indexCtrl",
}
}
})
.state('icerik', {
parent: "index",
url: "^/icerik",
views: {
"viewA": {
templateUrl: "icerik.html",
controller: "indexCtrl",
},
}
})
.state('icerik.icerikDetails', {
url: "/icerik/:id",
template: "<div>{{manga}}</div>",
controller: "mmgCtrl",
resolve: {
getData: function(MY, $stateParams, $filter) {
return MY.isimler.then(function(res) {
return $filter('filter')(res.data, {
id: $stateParams.id
}, true)[0];
});
}
}
})
$urlRouterProvider.otherwise("/");
These will be new controllers and factory:
.factory('MY', function($http) {
var factory = {};
//var url = '/uzak/remote.php?callback=JSON_CALLBACK';
var url = 'data.json';
factory.isimler = $http.get(url);
return factory;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen) {
$scope.mangas = alHemen;
});
})
.controller('mmgCtrl', function($scope, getData) {
//$scope.manga = getData.then(function(data){
// $scope.details = data;
// });
$scope.manga = getData;
})
And an example of templates "index.tpl.html":
<div >
<h2> this is index view</h2>
icerik
<div ui-view="viewA"></div>
</div>
and "icerik.html":
<div class="row" >
<div class="col s12 m6 l4" ng-repeat="manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="icerik.icerikDetails({id:manga.id})" class="thumbnail">
img src="/kapaklar/{{manga.kapak}}"
</a>
</div>
</div>
</div>
<hr>
<div ui-view=""></div>
</div>
Check it here

Categories

Resources