AngularJS UI Router reload not working - javascript

I have two states in my current apps, which is login and register. If I just open my website towards localhost:8001, it is automatically redirect to /login because I've set
$urlRouterProvider.otherwise('/login')
But if I open my website towards localhost:8001/asdf, it does not redirect to /login. It just print not found.
What am I missing?
Here is my full code
app.module.js
var myApp = angular.module('myApp', ['routesApp']);
app.routes.js
var routesApp = angular.module('routesApp', ['ui.router','loginApp']);
routesApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/login');
$locationProvider.html5Mode(true);
}]);
login.routes.js
routesApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'app/components/login/login.html',
controller: 'loginController'
});
});
register.routes.js
routesApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('register', {
url: '/register',
templateUrl: 'app/components/register/register.html',
});
});
login.controller.js
var loginApp = angular.module('loginApp', ['ngAnimate']);
loginApp.config(function($sceDelegateProvider, $httpProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
'self'
])
});
var loginController = function($scope){
//test controller
}
loginApp.controller('loginController', loginController);
index.html
<!DOCTYPE html>
<html>
<head>
<title>MyApp</title>
<base href="/">
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CSS -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<link href="assets/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet/less" type="text/css" href="assets/less/phinisi.less">
<link rel="stylesheet/less" type="text/css" href="assets/less/dropdown.less" />
<!-- JavaScript -->
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="bower_components/angular-animate/angular-animate.min.js"></script>
<script src="assets/js/angular-payments.js"></script>
<script src="assets/js/jquery-2.1.3.min.js"></script>
<script src="assets/js/bootstrap.js"></script>
<script src="assets/js/ui-bootstrap-0.12.1.min.js"></script>
<script src="app/app.module.js"></script>
<script src="app/app.routes.js"></script>
<!-- Login Script -->
<script src="app/components/login/login.controller.js"></script>
<script src="app/components/login/login.routes.js"></script>
<!-- Register Script -->
<script src="app/components/register/register.routes.js"></script>
<script src="assets/js/less.js"></script>
</head>
<body ng-app="myApp">
<div ui-view></div>
</body>
</html>

The problem is that you are using html5mode but it appears your server is not set to properly forward requests to your index for Angular to handle.
The server is attempting to find a resource at this location and failing. The reason this did not happen previously, is because the # that is present when html5mode is disabled causes the browser to recognize that the rest of the URL is not a navigable path. The path prior to the # is your index.html file, where Angular exists and knows to handle routing based on the proceeding URI path.
Since I'm not sure what server you are running on, I can't provide a specific answer, but this link provides answers for many of the commonly used servers:
How to: Configure your server to work with html5Mode
Please note, you'll need to make the change in your local build too. Here's an example using grunt with grunt-contrib-connect and connect-modrewrite
connect: {
options: {
hostname: 'localhost',
port: 8001,
middleware: function (connect, options) {
var modRewrite = require('connect-modrewrite');
var middlewares = [
modRewrite(['^[^\\.]*$ /index.html [L]'])
];
options.base.forEach(function (path) {
middlewares.push(connect.static(path));
});
return middlewares;
}
}
}
What this does is tells the server to route ALL requests back to index.html so that Angular can process the routing.

Related

Page not found while reload page during # removal

I have made changes in my index.html and app.js.
This is app.js file.
angular
.module('assessmentApp', ['ngRoute', 'ngCookies', 'ngSanitize', 'timer', 'assets', 'youtube-embed'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider', '$httpProvider'];
function config($routeProvider, $locationProvider, $httpProvider) {
/*$locationProvider.html5Mode({
enabled: true,
requireBase: false
});*/
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController',
controllerAs: 'vm'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController',
controllerAs: 'vm'
})
if(window.history && window.history.pushState){
$locationProvider.html5Mode({
enabled: true,
requireBase: true,
rewriteLinks: true
});
}
}
This is Index.html.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Assessment</title>
<meta name="description" content="">
<meta http-equiv=X-UA-Compatible content="IE=edge">
<meta name=viewport content="width=device-width,initial-scale=1">
<base href="/assessment/"></base>
</head>
</html>
I have followed all the solution which is present related to my problem but still my app not working.
I am using nginx server but I don't know is any changes requied or not? If yes then what change?
I added html5 api and base tag and i removed all # from my app html file so my app is working fine but when I am going to reload my application it return page not found
Make sure your server is set so that it is returning your index.html instead of a 404.
In your nginx config for this site add:
error_page 404 =200 /index.html;
Alternatively, you can redirect like this:
try_files $uri $uri/ /index.html;

App takes too long to load in production

I have pushed my angular 2 app on heroku but it takes too long to load.
is there a way to bundle everything up because right now i have this in my index.html
<html>
<head>
<base href="/">
<title>Angular 2 Arc</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<ng2-app>Loading...</ng2-app>
<!-- Load Angular 2 Core libraries -->
<script src="es6-shim/es6-shim.min.js"></script>
<script src="systemjs/dist/system-polyfills.js"></script>
<script src="angular2/bundles/angular2-polyfills.js"></script>
<script src="systemjs/dist/system.src.js"></script>
<script src="rxjs/bundles/Rx.js"></script>
<script src="angular2/bundles/angular2.dev.js"></script>
<script src="angular2/bundles/router.dev.js"></script>
<script src="angular2/bundles/http.js"></script>
<!-- Load Bootstrap and Jquery -->
<script src="lib/jquery/jquery.min.js" charset="utf-8"></script>
<script src="lib/bootstrap/js/bootstrap.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" />
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="assets/css/app.css">
<!-- Configure SystemJS -->
<script>
System.config({
defaultJSExtensions: true,
packages: {
boot: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('js/boot')
.then(null, console.error.bind(console));
</script>
</body>
</html>
My setup is express server and system JS.
server.js
var express = require('express');
var bodyParser = require('body-parser')
var fs = require("fs");
// initialize express
var app = express();
// declare build and node_module paths
app.use(express.static("./build"));
app.use(express.static("./node_modules/"));
// parse request body
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var body;
// route to send json data from angular 2
app.post('/export', function(req, res){
body = req.body;
res.json("Got the data!");
fs.writeFile('parameters.json', JSON.stringify({body}, null, 4), function (err) {
if (err) return console.log(err);
console.log('Data json file created!');
});
});
// start server
app.listen(process.env.PORT || "3001", function(){
console.log("Express server running on localhost:3001");
});
If its the free heroku tier its probably because its sleeping when you request it?
You can minify and concatenate your js files to decrease load times.
Here is a guide on how to do that with gulp tasks:
https://caveofcode.com/2016/03/gulp-tasks-for-minification-and-concatenation-of-dependencies-in-angularjs/

AngularJS + RequireJS. Unknown provider: $routeProvider?

I am trying to use Angular with RequireJS, and am having a problem with Angular routing. The error I receive is " Unknown provider: $routeProvider" so I know that the ngRoute dependency is not working. I have no idea why. Here is my code below, can someone please help me?
index.html
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<!-- <script src="js/vendor/modernizr-2.8.3.min.js"></script> -->
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<div id="main">
<div ng-view>
</div>
<script data-main="js/main" src="js/vendor/require.js">
</body>
</html>
main.js
require.config({
paths: {
'angular': 'vendor/angular',
'domReady': 'vendor/domready',
'ngRoute': 'vendor/angular-route'
},
shim: {
'angular': {
exports: 'angular'
},
'ngRoute': {
deps: ['angular']
}
},
deps: ['./bootstrap']
});
bootstrap.js
/**
* bootstraps angular onto the window.document node
*/
require([
'require',
'angular',
'ngRoute',
'./app',
'./routes'
], function (require, ng) {
'use strict';
require(['domReady!'], function (document) {
ng.bootstrap(document, ['app']);
});
});
app.js
define('app',
[
'angular',
'ngRoute'
], function(ng) {
'use strict';
console.log('app.js loaded');
var app = ng.module('app', ['ngRoute']);
console.log(app);
return app;
});
routes.js
require(['app'], function(app) {
'use strict';
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: './views/home.html',
controller: 'homeCtrl'
});
}]);
});
I fixed the problem myself. Here is my new main.js and bootstrap.js Hope it might help someone else having trouble with RequireJS + ngRoute. I still need to seperate my app.config into another file, but for now this solution is working nicely. Thank goodness.
main.js
require.config({
paths: {
'angular': 'vendor/angular',
'domReady': 'vendor/domready',
'angularRoute': 'vendor/angular-route'
},
shim: {
'angular': {
exports: 'angular'
},
'angularRoute': {
deps: ['angular'],
exports: 'angularRouter'
}
},
deps: ['./bootstrap']
});
bootstrap.js
require(['angular', 'angularRoute'], function (angular, angularRoute) {
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'js/views/home.html'
})
.otherwise('/');
});
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
});

Using Ionic - Cannot get Firebase to load properly - Error: Module 'firebase' is not available

I have looked at the following questions and have not been able to find an effective solution, hence I am posting another question.
Ionic + firebase, error Module 'firebase' is not available
Firebase, AngularFire Error: Module firebase is not available
Angularfire 'Firebase' is not defined
I am very much a beginner and this is my first Ionic app using Firebase. I am simply trying to get Firebase to load properly. I have included the following CDNs in my index.html:
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">
-->
<!--firebase-->
<script src="https://cdn.firebase.com/js/client/2.2.1/firebase.js"></script>
<!--angularfire-->
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"></script>
<!-- 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/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<!--
The nav bar that will be updated as we navigate between views.
-->
<ion-nav-bar class="bar-stable">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<!--
The views will be rendered in the <ion-nav-view> directive below
Templates are in the /templates folder (but you could also
have templates inline in this html file if you'd like).
-->
<ion-nav-view></ion-nav-view>
</body>
</html>
app.js:
angular.module('starter', ['ionic', 'firebase', 'starter.controllers', 'starter.services'])
.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 && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: "/tab",
abstract: true,
templateUrl: "templates/tabs.html"
})
// Each tab has its own nav history stack:
.state('tab.login', {
url: '/login',
views: {
'tab-login': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl'
}
}
})
.state('tab.new', {
url: '/new',
views: {
'tab-new': {
templateUrl: 'templates/tab-new.html',
controller: 'NewCtrl'
}
}
})
.state('tab.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/tab-home.html',
controller: 'HomeCtrl'
}
}
})
.state('tab.profile', {
url: '/profile',
views: {
'tab-profile': {
templateUrl: 'templates/tab-profile.html',
controller: 'ProfileCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/home');
});
controller.js:
angular.module('starter.controllers', ['ionic', 'firebase', 'starter.services'])
.controller('LoginCtrl', function($scope) {
})
.controller('NewCtrl', function($scope) {})
.controller('HomeCtrl', function($scope, Chats) {
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
}
})
.controller('ProfileCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
With this code, I get the errors:
Uncaught ReferenceError: angular is not defined(anonymous function) # angularfire.min.js:12(anonymous function) # angularfire.min.js:12
ionic.bundle.js:8762 Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
Error: [$injector:modulerr] Failed to instantiate module firebase due to:
Error: [$injector:nomod] Module 'firebase' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.3.13/$injector/nomod?p0=firebase
at REGEX_STRING_REGEXP (http://localhost:8100/lib/ionic/js/ionic.bundle.js:8762:12)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:10466:17
at ensure (http://localhost:8100/lib/ionic/js/ionic.bundle.js:10390:38)
at module (http://localhost:8100/lib/ionic/js/ionic.bundle.js:10464:14)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:12796:22
at forEach (http://localhost:8100/lib/ionic/js/ionic.bundle.js:9022:20)
at loadModules (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12780:5)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:12797:40
at forEach (http://localhost:8100/lib/ionic/js/ionic.bundle.js:9022:20)
at loadModules (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12780:5)
http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=firebase&p1=Error%…%3A%2F%2Flocalhost%3A8100%2Flib%2Fionic%2Fjs%2Fionic.bundle.js%3A12780%3A5)
at REGEX_STRING_REGEXP (http://localhost:8100/lib/ionic/js/ionic.bundle.js:8762:12)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:12819:15
at forEach (http://localhost:8100/lib/ionic/js/ionic.bundle.js:9022:20)
at loadModules (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12780:5)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:12797:40
at forEach (http://localhost:8100/lib/ionic/js/ionic.bundle.js:9022:20)
at loadModules (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12780:5)
at createInjector (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12706:11)
at doBootstrap (http://localhost:8100/lib/ionic/js/ionic.bundle.js:10144:20)
at bootstrap (http://localhost:8100/lib/ionic/js/ionic.bundle.js:10165:12)
http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=starter&p1=Error%3…3A%2F%2Flocalhost%3A8100%2Flib%2Fionic%2Fjs%2Fionic.bundle.js%3A10165%3A12)
I did not include the angular CDN because ionic includes it.
I already created a new app on firebase, and can access it through the firebase dashboard.
Any ideas how to get firebase up and running correctly?
You need to move ionic.bundle.js before angularfire.min.js, Because angular fire.js using angular object while creating module & it is throwing an error.

Angularjs 1.2.x Injector:modulerrr error even a after adding ngRoute

I am teaching myself angularjs and I can't seem to crack this error. I have tried trouble shooting. Given up, here is what I got.
index.html
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Simple App</title>
</head>
<body>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="_js/main.js"></script>
</body>
</html>
main.js
var app = angular.module("myApp", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "_templates/home.html",
controller: 'HomeController'
})
.otherwise({ redirectTo: '/' });
});
app.controller('HomeController', function() {
});
error
Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.2.23/$injector/modulerr?p0=myApp&p1=Error%3A%…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.23%2Fangular.min.js%3A18%3A170)
angular.js:36(anonymous function) angular.js:36(anonymous function)
angular.js:3906r angular.js:325e angular.js:3872gc angular.js:3812c
angular.js:1444fc angular.js:1459Xc angular.js:1368(anonymous
function) angular.js:21949a angular.js:2573(anonymous function)
angular.js:2853r angular.js:325c angular.js:2852
http://jsfiddle.net/r91ymsu3/
You need to include ng-route module script also for routing
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>

Categories

Resources