Angular ui-router customization issue - angularjs

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'
});
}
})();

Related

angularJs navigation's from ng-route to ui-router

I am new to AngularJS, and I am a little confused of how I can use angularjs ui-router in the following scenario:
It consists of two sections. The first section is the Homepage with its login and sign up views, and the second section is the Dashboard (after a successful login).
When I logged in success need to navigate from login form to "Home page".
When I tapped a registration button I need to navigate to "Registration page" from login page
Similarly I also need a "forgot password" screen
My current router is below. How can I do this functionality? (Please help with some HTML code and related controllers)
app.js:
'use strict';
//Define Routing for app
angular.module('myApp', []).config(['$routeProvider', '$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'RegisterController'
})
.when('/forgotPassword', {
templateUrl: 'forgotpassword.html',
controller: 'forgotController'
})
.when('/home', {
templateUrl: 'views/dashBoard.html',
controller: 'dashBordController'
})
.otherwise({
redirectTo: '/login'
});
}]);
});
Firstly, nobody will design a website with your requirements / functionalities for you. stackoverflow is for specific problems, your questions is too broad, more about it - How to Ask. But to help you with a conversion from ngRoute to ui.router I can describe what the syntax should look like so you can adopt it for your website.
Converting to ui.router
Your config doesn't change that much. you need to replace .when with .state, use the right providers, and have the right syntax. Here is an example with just few states:
app.config(config);
/* your preferred way of injecting */
config.$inject = ['$stateProvider', '$urlRouterProvider'];
function config($stateProvider, $urlRouterProvider) {
$stateProvider.
state("HomepageState", {
url: "/home",
templateUrl: 'views/dashBoard.html',
controller: 'dashBordController'
}).
state("RegisterState", {
url: "/register",
templateUrl: 'register.html',
controller: 'RegisterController'
})
/*
more can be added here...
*/
$urlRouterProvider.otherwise('/login');
}
Navigation
You should be using states for navigation at all times. So replace href="url" with ui-sref="state". Here are some examples of anchor links:
<a ui-sref="HomepageState">Home page</a>
<a ui-sref="RegisterState">Register</a>
Don't forget to replace your ng-view with ui-view. (For older browser support it's better to have <div ui-view></div> instead of <ui-view></ui-view>)
Redirection
After filling in a login form, the user will press something like:
<button ng-click="login()">Sign in</button>
which will call a function login() that will validate / verify if the user can be logged in. (You can also have <form ng-submit="login()"> with <button type="submit">...) Then, if everything is fine and the user got his session / cookie, you can have a redirection to another page with:
$state.go("HomepageState");
(Don't forget to inject $state into your controller)
Advanced navigations
In the future if you have user profiles that are listed by their index. Your routing can be improved with $stateParams. Their job is to check any additional parameters in the URL. For example: a URL: /profile/721 can have a state with url:"/profile/:id". Then you can extract that id with $stateParams.id and use it in your controllers. And your redirection would look like:
$state.go("ProfileState", { "id": 721});

Transition from ng-view to ui-view

I have an older app (Angular 1.5.3) and I would like to take advantage of angular-ui-router and components for a few of my pages.
Is it possible to use the old routeProvider in conjunction with the stateProvider that ui-router provides?
IE I would like to transition a few pages to use components here and there as I get time, while leaving the rest.
I am pretty sure using ng-view and ui-view I am having a hard time getting that to work (probably cause you are not supposed to do that). Does that mean I have to transition my entire project from routeProvider to stateProvider all at once?
Is it possible to use the old routeProvider in conjunction with the
stateProvider that ui-router provides?
Short answer
No. Similar structure but different syntax
Long answer
No, but ... You can easily convert ng-view to ui-view a.e. from $routeProvider to $stateProvider.
Consider example ng-view:
$routeProvider
.when('/Book/Add', {
template: '<div class="box" ng-class="classname">Add</div>',
controller: function($scope) {$scope.classname="add"}
})
.when('/Book/Error', {
templateUrl : 'error.html',
controller: 'ErrorController'
})
.otherwise({redirectTo: '/Book/Error'});
Consider example ui-view:
$stateProvider
.state('book', {
url: '/Book',
abstract: true,
templateUrl: 'views/Book.html'
})
.state('book.add', {
url: '/inbox',
template: '<div class="box" ng-class="classname">Add</div>',
controller: function($scope) {$scope.classname="add"}
})
.state('book.error', {
url: '/Error',
templateUrl : 'error.html',
controller: 'ErrorController'
})
$urlRouterProvider.otherwise(function ($injector, $location) {
return '/Book/Error';
});
Keep in mind that routing syntax will change too.
For example:
if ($state.current.name === 'login') {
$state.go('book.add', {});
}
Instead Add we will write <a ui-sref="book.add">Add</a>
And so on ......
As you can see, the syntax is a bit similar. I'm sure you will find a lot of references about power of $stateProvider. For example https://stackoverflow.com/a/21024270/1631379
Hope I answered on your question

Angular ui-router parameter causes conflicts with other states

Just to give some context, I have an Angular application with several separate modules. I am working with ui-router to provide routing to these modules, and I want to use the names of the modules in the URLs. In my Angular app config block I have defined a state for both module1 and module2 with a parameter on each like so:
.state('module1', {
url: '/:module_name',
templateUrl: '/app/modules/module1/views/index.html',
controller: 'someCtrl'
})
.state('module2', {
url: '/:module_name',
templateUrl: '/app/modules/module2/views/index.html',
controller: 'someOtherCtrl'
})
I also have a few links that should take me to the home page of each module.
Naturally, the problem is that the first state will catch all of the rest of my module2 routes, since their URLs all have the same form:
http://localhost:3000/#/module1
http://localhost:3000/#/module2/users
http://localhost:3000/#/module2/books
and so on. I can see how the order that we define the stats is important, but I can't seem to come up with a way to be able to have the module name as a state parameter (this is important since I need it in the corresponding controllers to distinguish from which module an operation is coming from) and avoid this hierarchy problem altogether.
Any ideas?
In your case ui-router will not know which route your are pointing to as they are exactly the same. You would either have to hardcode the module name(assuming there are only a few):
.state('module1', {
url: '/module1',
templateUrl: '/app/modules/module1/views/index.html',
controller: 'someCtrl'
})
.state('module2', {
url: '/module2',
templateUrl: '/app/modules/module2/views/index.html',
controller: 'someOtherCtrl'
})
.state('module2', {
url: '/module2/users',
templateUrl: '/app/modules/module2/views/users.html',
controller: 'someOtherCtrl'
})
.state('module2', {
url: '/module2/books',
templateUrl: '/app/modules/module2/views/books.html',
controller: 'someOtherCtrl'
})
or dynamically inject the html based on the module number
.state('module', {
url: '/module/:moduleId',
templateUrl:
function (stateParams){
return '/app/modules/module' + stateParams.moduleId + '/views/index.html';
}
controller: 'someOtherCtrl'
})
so now to hit module one the path looks like this
http://localhost:3000/#/module/1

AngularJS page blank after refresh

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.

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').

Resources