Here is my app.js route file in AngularJS
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/login', {
title: 'Login',
templateUrl: 'resources/views/layouts/loginUser.php',
controller: 'authCtrl'
})
.when('/', {
title: 'Login',
templateUrl: 'resources/views/layout/login.php',
controller: 'logoutCtrl'
})
.when('/reset', {
title: 'Reset Password',
templateUrl: 'resources/views/layouts/forgetPassword.php',
controller: 'authCtrl'
})
.when('/invalidtoken', {
title: 'Login',
templateUrl: 'resources/views/layout/invalidtoken.php',
controller: 'authCtrl',
role: '0'
})
//$locationProvider.html5Mode(true);
}])
.run(function ($rootScope, $location, Data, $http) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
var nextUrl = next.$$route.originalPath;
if (nextUrl == '/signin' || nextUrl == '/login' || nextUrl == '/verify' || nextUrl == '/register' || nextUrl == '/registered' || nextUrl == '/reset' || nextUrl == '/resetdone' || nextUrl == '/registersuccess')
{
$location.path(nextUrl);
}
else
{
$location.path('/');
}
});
});
Here i use .run to handle few requests.
I want to remove the # from the url to make the url pretty,
So i did like this to remove the # as suggested here
app.config(['$routeProvider', '$locationProvider'
function ($routeProvider, $locationProvider) {
and in the last line
$locationProvider.html5Mode(true);
But nothing is happening to the application, it stills haves # in the url.
Even i tried this way
How can i achieve this ?
Update :
If i do
.run(function ($rootScope, $location, Data, $http, $locationProvider) {
and in the last line
$locationProvider.html5Mode(true);
I am getting this error
Error: $injector:unpr
Unknown Provider
I have tried in many ways, but none of them working.
Update 2 :
Or can anyone suggest a link of angularjs example which provides example without # in url ?
Why do you want to use the .run() ? Add <base href="/" /> to you <head> or start of your body (first line) and then to match the logic of your .run() try this ( .otherwise("/path") to your $routeProvider):
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.
when('/login', {
title: 'Login',
templateUrl: 'resources/views/layouts/loginUser.php',
controller: 'authCtrl'
})
.when('/', {
title: 'Login',
templateUrl: 'resources/views/layout/login.php',
controller: 'logoutCtrl'
})
.when('/reset', {
title: 'Reset Password',
templateUrl: 'resources/views/layouts/forgetPassword.php',
controller: 'authCtrl'
})
.when('/invalidtoken', {
title: 'Login',
templateUrl: 'resources/views/layout/invalidtoken.php',
controller: 'authCtrl',
role: '0'
})
. otherwise("/");
$locationProvider.html5Mode(true);
}]);
If you still face issues, I recommend https://github.com/angular-ui/ui-router
Update:
your index.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Green Hopping</title>
<link rel="shotcut icon" type="favicon.ico" href="public/images/favicon.ico" />
<link rel="icon" type="favicon.ico" href="public/images/favicon.ico" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.2/angular-route.min.js"></script>
</head>
<body ng-cloak="">
<base href="/">
<div data-ng-view="" id="ng-view" class="slide-animation"></div>
</body>
<script>
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
title: 'Home',
templateUrl: 'home.html',
controller: 'homeCtrl'
})
.when('/login', {
title: 'Login',
templateUrl: 'login.html',
controller: 'authCtrl'
})
.when('/logout', {
title: 'Logout',
templateUrl: 'logout.html',
controller: 'logoutCtrl'
})
.when('/dashboard', {
title: 'Dashboard',
templateUrl: 'dashboard.html',
controller: 'dashboardCtrl'
})
.otherwise('/');
$locationProvider.html5Mode(true);
}])
.run(function ($rootScope, $location, $http, loginSrv) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
var nextUrl = next.$$route.originalPath;
var orUseUrl = $location.path();
console.log(nextUrl);
if (nextUrl === '/logout'){loginSrv.logout();}
if (nextUrl === '/login'){loginSrv.login();}
if (loginSrv.loggedin === false) { $location.path('/'); }
else { $location.path(nextUrl); }
});
});
app.service("loginSrv",function(){
var ls= this;
ls.loggedin = false;
ls.logout = function(){
ls.loggedin = false;
}
ls.login = function(){
ls.loggedin = true;
}
});
app.controller("homeCtrl",function($scope, loginSrv){
$scope.loggedin = loginSrv.loggedin;
})
app.controller("dashboardCtrl",function($scope, loginSrv){
$scope.loggedin = loginSrv.loggedin;
})
app.controller("authCtrl",function($scope, loginSrv){
$scope.loggedin = loginSrv.loggedin;
})
app.controller("logoutCtrl",function($scope, loginSrv){
$scope.loggedin = loginSrv.loggedin;
})
</script>
</html>
All other templates are same like this. Copy paste the following for home.html , login.html , dashboard.html , logout.html . Plunker will not be able to show issues with routes for client side. Try this. This is completely functional code.
<div>
<div>Home |
Login |
Dashboard |
Logout</div>
<div> This is from the home/login/dashboard/logout Controller. Loggedin: {{loggedin}}</div>
</div>
try changing:
$locationProvider.html5Mode(true);
To:
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
You can't inject $locationProvider in .run because providers are only available for .config
This answer should help but you will have 2 issues:
You will need a check before $locationProvider.html5Mode(true) as it will not work on IE 10 or older.
if(window.history && window.history.pushState){
$locationProvider.html5Mode(true);
}
This will work only by removing the # when the user enters it in the url, i.e. if the users types app/#/login it will change to app/login. However, if the user bookmarks or copies the changed url app/login and enters that in the browser he will get an error as the server does not know about angular routing since it is client side only. In the thread I linked above you may find some comments on how to fix this.
Are you by chance receiving a 404 error ? Whenever you change the mode to html5history you have to tell the web server to always return the index page no matter what URL is requested. As the angular docs says here:
https://docs.angularjs.org/guide/$location
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html). Requiring a <base> tag is also important for this case, as it allows Angular to differentiate between the part of the url that is the application base and the path that should be handled by the application.
Have you tried doing that and configured it properly ?
Also remember that you have to specify the base entry href of your application for it to work like
<base href="/" />
The problem is it is missing the service injection.
So in config section try injecting $locationProvider like below.
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.
when('/login', {
title: 'Login',
templateUrl: 'resources/views/layouts/loginUser.php',
controller: 'authCtrl'
})
.when('/', {
title: 'Login',
templateUrl: 'resources/views/layout/login.php',
controller: 'logoutCtrl'
})
.when('/reset', {
title: 'Reset Password',
templateUrl: 'resources/views/layouts/forgetPassword.php',
controller: 'authCtrl'
})
.when('/invalidtoken', {
title: 'Login',
templateUrl: 'resources/views/layout/invalidtoken.php',
controller: 'authCtrl',
role: '0'
})
$locationProvider.html5Mode(true);
}])
With html5mode you have to specify the base url in your html file for eg,
<base href="/">
Some links you can go through for your reference,
https://docs.angularjs.org/error/$location/nobase
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag
it does not look possible you to remove hash-bang (#) from href manually, and it causes malfunction your router because hashbangs are enables browser not treat your state in order to send get request to an end point. browser does not fire a get request over #/route while it does over /route, unless you use your url provider in html5 mode. For html5 mode, add the line below into your app.config function:
$locationProvider.html5Mode(true).hashPrefix('!')
Related
I have developed an application in AngularJS. My application have 2 controllers and 5 templates. This application works absolutely fine on Android and Windows platform. But, whenever I try to access this application on iOS it gives me following error
Error: [$compile:tpload]
I have tried to switch to the template that's working fine and render on load. But, the error is still the same.
I am suspecting some issue with my app.js but not really definite.
var App = angular.module('myApp',['ngRoute', 'ngCookies','ngDialog'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
controller: 'FirstController',
templateUrl: 'templates/FirstPage.html',
controllerAs: 'ctrl'
})
.when('/home1', {
controller: 'FirstController',
templateUrl: 'templates/SecondPage.html',
controllerAs: 'ctrl'
})
.when('/home2', {
controller: 'FirstController',
templateUrl: 'templates/thirdPage.html',
controllerAs: 'ctrl'
})
.when('/loginRedirect', {
controller: 'LoginController',
templateUrl: 'templates/LoginRedirect.html',
controllerAs: 'vm'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'templates/Login.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/login' });
}
run.$inject = ['$rootScope', '$location', '$cookies', '$http','ngDialog'];
function run($rootScope, $location, $cookies, $http,ngDialog) {
// keep user logged in after page refresh
$rootScope.globals = $cookies.getObject('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata;
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
var restrictedPage = ['/login'].indexOf($location.path()) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (!restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
When I execute my application my login page display perfectly fine. On login it redirects me to loginRedirect page. But, when I try to access any page after that i.e. FirstPage, SecondPage or thirdPage it throws me following exception.
But, remember these problems only happen when I access my application on any iOS machine. i.e. iPhone (Safari or Chrome), iPad (Safari or Chrome).
I hope anyone had same issue or probably have the solution for this problem.
I have a problem with my angularjs routes. My simplified route config looks like:
App.config([ '$routeProvider', function( $routeProvider ) {
$routeProvider.
when('/', {
redirectTo: '/home'
}).
when('/home', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
}).
when('/404', {
templateUrl: '404.html'
}).
when('/500', {
templateUrl: '500.html'
}).
when('/:tabName', {
templateUrl: 'tabView.html',
controller: 'TabContentCtrl'
}).
when('/:tabName/:widgetName', {
templateUrl: 'tabView.html',
controller: 'TabContentCtrl'
}).
otherwise({
redirectTo: '/404'
});
}]);
The problem is when I put URLs http://myapp or http://myapp/ into browser, it redirects me nowhere, nothing takes place, even redirect to 404 error page. It starts working when I put hash to URL http://myapp/#, then it works as I expected. But why my default route for root URL of application http://myapp, and http://myapp/ did not work?
You just need to enable html5mode:
config javascript
App.config([ '$routeProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
}]);
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<base href="/">
</head>
</html>
It depends on how have you set your virtual host and is it pointing to your root index.html? If yes, then if you type http://myapp it would definitely take you to http://myapp/#/home
I'm trying to create so-called 'SEO-friendly' URLs in AngularJS.
In my script.js for the routing I have:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.html5Mode(true);
when('/blog', {
templateUrl: 'blog.html',
controller: 'BlogController'
}).
when('/page/ideas', {
templateUrl: 'ideas.html',
controller: 'IdeasController'
}).
otherwise({
templateUrl: 'home.html'
});
}]);
app.controller("BlogController", function($scope) {
$scope.title = 'Blog';
});
app.controller("IdeasController", function($scope) {
$scope.title = 'Ideas';
});
To remove the # from the URL, I am enabling the html5 mode with:
$routeProvider.html5Mode(true);
however, this results in the following error:
Failed to instantiate module exampleApp due to:
TypeError: $routeProvider.html5Mode is not a function
Does anyone have a solution for this issue? It means that the content will not display from the views because of it.
Edit: for anyone wondering, the working code is:
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/blog', {
templateUrl: 'blog.html',
controller: 'BlogController'
}).
when('/page/ideas', {
templateUrl: 'ideas.html',
controller: 'IdeasController'
}).
otherwise({
templateUrl: 'home.html'
});
$locationProvider.html5Mode(true);
}]);
html5mode method is available there on $locationProvider provider.
You should include $locationProvider in your config phase to make that dependency available in config block & then enable html5mode for # free URL.
Code
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
//$routerProvider code here
$locationProvider.html5Mode(true);
}]);
Additionally you have to add <base href="/"> tag on the index.html page
I have been making an app in AngularJS with Angular-ui-router based on Ionic Framework. It works perfect on the desktop in every web browser, but it does not show anything on my mobile (after build I run it on 2 devices). The problem is that it doesn't load template inside ui-view.
I have got an index.html file, the body section is below (in head section there is everything included):
<body ng-app="starter">
<div ui-view=""></div>
</body>
And the part of app.js - run and config.
angular.module('starter', ['ionic', 'ngStorage', 'ngAnimate', 'naif.base64', 'ui.router'])
.run(function($ionicPlatform, $rootScope, $location) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
history = [];
$rootScope.$on('$routeChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
history.back();
};
})
.config(function($stateProvider, $urlRouterProvider) {
"use strict";
$stateProvider
.state('connectionCheck', {
url: '/',
controller: ['$scope', '$location', '$http',
function($scope, $location, $http) {
$http.get('http://pingurl.com')
.success(function(data) {
jdata = data;
if (data.status === "success") {
$location.path('/login');
}else{
$location.path('/error');
}
})
.error(function() {
$location.path('/error');
});
$scope.retry = function() {
$location.path('/');
};
}
]
})
.state('login', {
url: '/login',
templateUrl: 'login.html'
})
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: ['$scope', '$location', '$localStorage',
function($scope, $location, $localStorage) {
$scope.username = $localStorage.username;
$scope.token = $localStorage.token;
$scope.email = $localStorage.email;
$scope.goToAlerts = function() {
$location.path('/alerts');
};
$scope.goToSettings = function() {
$location.path('/settings');
};
$scope.goToLocation = function() {
$location.path('/location');
};
$scope.goToSymptoms = function() {
$location.path('/symptoms');
};
$scope.getClass = function(path) {
if ($location.path().substr(0, path.length) == path) {
return "active"
} else {
return ""
}
};
}
]
})
.state('error', {
url: '/error',
templateUrl: 'error.html'
})
.state('register', {
url: '/register',
templateUrl: 'register.html',
})
.state('push', {
url: '/push',
templateUrl: 'push.html',
})
.state('alerts', {
url: '/alerts',
templateUrl: 'alerts.html'
})
.state('newSymptom', {
url: '/newSymptom',
templateUrl: 'newsymptom.html'
})
.state('symptoms', {
url: '/symptoms',
templateUrl: 'symptoms.html'
})
.state('newAlert', {
url: '/newalert',
templateUrl: 'newalert.html'
})
.state('settings', {
url: '/settings',
templateUrl: 'settings.html'
})
.state('location', {
url: '/location',
templateUrl: 'location.html'
});
$urlRouterProvider.otherwise('/');
}).
//some controllers goes here
What I have already checked/tried to do?
I put example content to index.html - it worked.
I tried chanage the name of ui-view and add them in templateURL values of each state.
I changed the .html files to exlude error in them, but it did not helped.
Can anyone more experienced with Ionic/Angular give me a hint what is wrong here?
I seem to notice that it's often due to the modules you're loading in. So It's likely in this line.
angular.module('starter', ['ionic', 'ngStorage', 'ngAnimate', 'naif.base64', 'ui.router'])
Try checking each module by making sure:
You added it to your index.html
it's being called correctly
it's up to date
You can figure out by removing each, one at a time and then seeing if it works on the device.
Also know that AngularJS out of the box uses AngularUI Router and this uses a thing called routing for views. The UI-Router uses a thing called states that is the most used but the unofficial way for AngularJS and Ionic uses their own view state system that is basically the same thing as the UI-Router just with the Ionic namespace. So that is something you need to look up or you may find yourself running into a lot of walls during you builds because you are calling ui.router and I bet it's what's confusing your app, so remove it.
I'm trying to learn how routes work in AngularJS to make a little application that allows users to login and write comments in a live feed. However the whole concept of routes is a bit blurry for me atm and i can't get this right.
My standard index.html containing an ng-view and necessary scripts.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="//cdn.firebase.com/js/client/1.0.21/firebase.js"></script>
<script src="//cdn.firebase.com/libs/angularfire/0.8.2/angularfire.js"></script>
<script src="//cdn.firebase.com/js/simple-login/1.6.3/firebase-simple-login.js"></script>
<script src="controller.js"></script>
<title>Test Login App</title>
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
My controller containing module and routeprovider.
var myApp = angular.module('myApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'firebase',
'firebase.utils',
'simpleLogin'
]);
myApp.config(function($routeProvider) {
$routeProvider.
when('/', { controller: handleCtrl, templateUrl: 'handler.html' }).
when('/chatt', { controller: MyController, templateUrl: 'chat.html' }).
when('/login', { controller: loginCtrl, templateUrl: 'login.html' }).
otherwise({ redirectTo: '/handler' });
});
myApp.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
}])
myApp.controller('MyController', ['$scope', '$firebase',
function($scope, $firebase) {
//CREATE A FIREBASE REFERENCE
var ref = new Firebase("https://ivproj.firebaseio.com/");
// GET MESSAGES AS AN ARRAY
$scope.messages = $firebase(ref).$asArray();
//ADD MESSAGE METHOD
$scope.addMessage = function(e) {
//LISTEN FOR RETURN KEY
if (e.keyCode === 13 && $scope.msg) {
//ALLOW CUSTOM OR ANONYMOUS USER NAMES
var name = $scope.name || 'anonymous';
//ADD TO FIREBASE
$scope.messages.$add({
from: name,
body: $scope.msg
});
//RESET MESSAGE
$scope.msg = "";
}
}
}
]);
The $routeprovider function should direct me to handler that is a simple .html file containing two buttons that in turn redirects to other htmls.
I think you have the syntax of the otherwise call in your config section wrong. Change what you have for this instead:
otherwise('/handler');
hope this helps...
you are missing '' in controller part. correct code should look like -
myApp.config(function($routeProvider) {
$routeProvider.
when('/', { controller: 'handleCtrl', templateUrl: 'handler.html' }).
when('/chatt', { controller: 'MyController', templateUrl: 'chat.html' }).
when('/login', { controller: 'loginCtrl', templateUrl: 'login.html' }).
otherwise({ redirectTo: '/handler' });
});
Make sure that you are referring the correct path in templateUrl.
and look at my earlier post to get a better idea - How to navigate in Angular App
myApp.config(function($routeProvider) {
$routeProvider.
when('/', { controller: 'handleCtrl', templateUrl: 'handler.html' }).
when('/chat', { controller: 'MyController', templateUrl: 'chat.html' }).
when('/login', { controller: 'loginCtrl', templateUrl: 'login.html' }).
otherwise({ redirectTo: '/handler' });
});
The $routeProvider.when() method in the above code actually creates a route with the given configuration. And the three .when()'s are creating three different routes.
But in your $routeProvider.otherwise('/handler'), you are telling angular to go to a route called /handler if the user tries to navigate anywhere outside the configured routes.
The mistake you are doing here is, you did not define a route at /handler. So you need to first define that route and then use it in .otherwise().
Try changing your configuration to reflect the below.
myApp.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/handler', { controller: 'handleCtrl', templateUrl: 'handler.html' }).
when('/chat', { controller: 'MyController', templateUrl: 'chat.html' }).
when('/login', { controller: 'loginCtrl', templateUrl: 'login.html' }).
otherwise({ redirectTo: '/handler' });
});