AngularJS page blank after refresh - angularjs

I am building a web aplication with AngularJS. I am using ui-router and I have defined states like this:
//appContacts.js
(function () {
"use strict";
var app = angular
.module('appContacts', ['ui.router', 'angularUtils.directives.dirPagination'])
.config(['$stateProvider', '$locationProvider', '$urlRouterProvider',
function ($stateProvider, $locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("home", {
url: "/",
templateUrl: "views/contactsView.html",
controller: "contactsController",
controllerAs: "vm"
})
.state("organization", {
url: "/organizations/:Id",
templateUrl: "views/organizationDetail.html",
params: { Id: null },
controller: "organizationsController",
controllerAs: "vm"
})
.state("contact", {
url: "/contact/:Id",
templateUrl: "views/contactDetails.html",
params: { Id: null },
controller: "contactsDetailController",
controllerAs: "vm"
})
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: true
});
$locationProvider.html5Mode(true);
}
]);
})();
I get requested information from the Database using HTTP methods. I have two issues:
When I refresh the page the page get blank. Any idea what I am doing wrong?
The home page controller calls automatically the HTTP methods that populate a table using ng-repeat. That means that it is impossible to visit another page directly like http://localhost:50895/contact/the-id because there is not data stored. I always have to visit the home page to load the data. How could I save and make available that data to all pages/states/controllers?
EDIT:
I have 4 error shown in the console.

Could you please debug it and check the browser console for any errors or exceptions??
There are three ways in which you can pass the data around:
a) Use $rootScope , but this is not considered as proper coding standard
b) Make use of the inbuilt .service() provided by AngularJs, this is a singleton object, means the value set into it in the first controller can be used anywhere down the line. But the value will be erased if you refresh the page.This is considered as better coding standard than using $rootScope
c) You can make use of localStorage or sessionStorage, using this the data can be retrieved even after the page refresh. Data will be stored as string, so parsing is needed.
There is one more way to store the data , Cookies. But this is used to store small string values.

Related

Angular ui-router customization issue

I am in trouble with a specific requirement here for our Application.
We a are setting-up an angular application inside a pre-existent Rails Application.
As a full refactor of our code-base is currently out-of-the-question we are dealing with some hard customization and hackings on both sides to allow a incremental introduction of Angular.
What we need for now is a way to tell the ui-router to bind only to the links we have the ng-sref attribute and do not bother with all the regular href links within our app.
Is there a way to achieve this behavior ?
Below is my current code:
angular.module('app').config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider.state('test', {
url: "/1/test",
template: 'test'
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: false
})
}
)
With this approach, all links, even those ones without any route setup for it, and without a ui-sref attribute, are being watched by angular routing service and prevented to work like it`s previous behaviour. I do not want to add every route of our huge app to the angular routing setup (this is a terrible idea) because most of theses links are to non-angular pages. I just want angular routing service to ignore this links, or these locations that are not defined. Maybe a setting for the $location service to let those guys fallow along with its previous behaviour (ajax requests, regular requests, or Turbolinks requests). I am pretty sure this is something really trivial that I might be missing the point.
What happens when I click on theses links is that the window location changes, but nothing happen. The browser request is not triggered.
Thank you very much in advance.
###################################################################################
# My suggestion is use the ui-router to route to specific pages as shown
# in the example below.
# <a ui-sref="/login">
# <a ui-sref="/logout">
# <a ui-sref="/signup">
# <a ui-sref="/profile">
# 'ui-sref' will take you to the specific pages.
# You can also use '$state.go' to take you to specific pages as shown below.
# $state.go('authentication.login');
# $state.go('authentication.logout');
# $state.go('authentication.signup');
# $state.go('authentication.profile');
###################################################################################
(function() {
'use strict';
angular
.module('app.foo.authentication')
.config(moduleConfig);
/* #ngInject */
function moduleConfig($translatePartialLoaderProvider, $stateProvider) {
$translatePartialLoaderProvider.addPart('app/foo/authentication');
$stateProvider
.state('authentication.login', {
url: '/login',
templateUrl: 'app/foo/authentication/login/login.tmpl.html',
controller: 'LoginController',
controllerAs: 'vm'
})
.state('authentication.logout', {
url: '/logout',
templateUrl: 'app/foo/authentication/logout/logout.tmpl.html',
controller: 'LogoutController',
controllerAs: 'vm'
})
.state('authentication.signup', {
url: '/signup',
templateUrl: 'app/foo/authentication/signup/signup.tmpl.html',
controller: 'SignupController',
controllerAs: 'vm'
})
.state('authentication.profile', {
url: '/profile',
templateUrl: 'app/foo/authentication/profile/profile.tmpl.html',
controller: 'ProfileController',
controllerAs: 'vm'
});
}
})();

Angular ui-router specific treatment for unknown state

I'm working on multiple angular apps that I have to nest (like a web portal). My main app got a router where I define some states.
$stateProvider
.state('state1', {
url: "/state1",
views: {
"area": { templateUrl: "area1.html"}
}
});
And my other apps work like this too. I'd like to make a specific script that would be called if the state called in the main app is unknown by the main router, so I could to get the url and views in another router.
For example, if the main app call the state state2 that is unknown by my first router, it will look for it in a second router which define it.
I looked for a solution using the resolve option of ui-router but I'm not sure it could work this way.
Feel free to ask for more details. I did my best to make it short and understandable :)
Documentation on Otherwise()
app.config(function($urlRouterProvider){
// if the path doesn't match any of the urls you configured
// otherwise will take care of routing the user to the specified url
$urlRouterProvider.otherwise('/index');
// Example of using function rule as param
$urlRouterProvider.otherwise(function($injector, $location){
... some advanced code...
});
})
Hope this code help you as your need:
var myApp = angular.module('myApp', []);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/state1');
$urlRouterProvider.when("", "/state1");
$stateProvider
.state('state1', {
url: '/state1',
templateUrl: 'state1.php'
}
})
.state("state2", {
url: "/state2",
templateUrl: 'state2.php'
});
});

Excluding path in url using AngularJS

My angular application has multiple pages which users can visit and I would like to hide all other urls and only show users the base url. So imagine my base url is: www.example.com and I have other pages like About, Contact Us etc. Currently, when the user clicks on About, the url changes to www.example.com/about. Is it possible for angular not to add the "/about"? Is this possible using angular js? Also, I have been searching for solutions and have experimented with ui-router.js, is it also possible with this module?
If you are using ui-router, then you can define states without specifying urls like
myApp.config(function($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/state1");
//
// Now set up the states
$stateProvider
.state('state1', {
url: "/state1",
templateUrl: "state1.html",
controller: 'Controller3'
})
.state('state2', {
templateUrl: "state2.html",
controller: 'Controller2'
})
.state('state3', {
templateUrl: "state3.html",
controller: 'Controller3'
})
});
So by default the url will be /state1. And you can implement navigation by using ui-sref directive in your template like ui-sref="state2" or using $state service in your controller like $state.go('state2').

How can I change my AngularJS routes to file?param1=a&param2=b format?

I need to change an existing AngularJS application from using URLs in the format:
example.com/thePage/#/section/1/subsection/1
To making the section & subsection parameters readable by the server with a format like so:
example.com/thePage?section=1&subsection=1
The environment does not offer something like mod_rewrite, so I need to change the routing in Angular to make it handle & generate these URLs. I believe I can do this using $locationProvider.html5Mode(true); however I’m not sure how to proceed from there. I’ve tried updating the existing routing to something like the below, however it fails to return a view (as if the routing isn’t working.
$stateProvider
.state('section', {
abstract: true,
url: '?section',
views: {
'header': {
template: '<h3></h3>'
},
'main': {
templateUrl: constants.baseUrl + 'views/section.html',
controller: 'sectionCtrl',
resolve: {
section: ['sectionervice', '$stateParams',
function (sectionervice, $stateParams) {
return sectionervice.getsection($stateParams);
}],
subsection: ['sectionervice', '$stateParams',
function (sectionervice, $stateParams) {
return sectionervice.getsubsection($stateParams);
}]
}
}
}
})
.state('section.detail.subsection', {
url: '&subsection=:sectionId',
views: {
'main': {
templateUrl: constants.baseUrl + 'views/section.detail.subsection.html',
controller: 'DictionaryCtrl'
}
}
});
It seems that $stateProvider may only work with the forward-slash(/) parameter delimiter. Is there another way to achieve this?
In the ui-router website has a simple example of you trying to do.
Maybe you can do the same thing, see the RouteProvider and StateProvider settings.
url: http://angular-ui.github.io/ui-router/sample/app/app.js
In the server side you can retrieve the url, so you can get your parameters.
[Edit]
About $locationProvider.html5Mode(true); you can do this and do the settings in route and state providers too, that don't interfere in functionality

AngularJS routing: detect if route/state is linked to or directly entered as url

Essentially how can I detect whether a specific route has been linked to from within an Angular application or accessed directly from a user typing that URL into the address bar from within the configuration phase?
I know I can listen for the $locationChangeSuccess event like follows:
$Scope.$on('$locationChangeSuccess', function(evt, newUrl, oldUrl) {
// -- do something with oldUrl --
});
on either $Scope or $rootScope but these instances are not available during the configuration phase.
Maybe I am making this more complicated than it needs to be but any help would be much appreciated.
Update
To give some context. Some of the routes in my application load the associated template into a modal window instead of into a standard view. I am using ui-router with the basic configuration below:
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider.state('index', {
url: '/',
templateUrl: 'index.html'
});
$stateProvider.state('foo', {
url: '/foo',
views: {
'': {
template: '='
},
modal: {
templateUrl: 'modal.html'
}
}
});
}
]);
And the main template:
<div class="main" ui-view></div>
<div ui-view="modal"></div>
This works fine if the user accessed /foo via a link (ui-sref="foo") however the problem I have is that if the /foo route is entered directly into the address bar the underlying template does not exist obviously. I could manually set it if the page is accessed in this way instead. So if I can tell where the request has come from then I can set the template accordingly but it needs to be done in the configuration phase above (at least I think it does).
Note that if I were set the template explicitly it would be reloaded on each request to /foo which is not the desired result.
I can propose a solution, but i'm not sure it will make sense in the context of your application.
You could have the foo route be a sub route of the index route:
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider.state('index', {
url: '/',
templateUrl: 'index.html'
});
$stateProvider.state('index.foo', {
url: '/foo',
views: {
'modal#': {
templateUrl: 'modal.html'
}
}
});
});
<div ui-view></div>
<div ui-view="modal"></div>
The 'downside' of this method is that if you need to reuse the modal in any other part of the application, you need to redefine the state declaration for each of the top level state you need them in.
If you find a better solution, please ping this answer, as i'm trying to solve a very similar problem.

Resources