Currently I am able to add routing mechanism in AngularJs with the following code :
App.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : '/templates/home.html',
controller : 'landing'
})
.when('/login', {
templateUrl : '/templates/login.html',
controller : 'login'
});
});
What I need is an url in the format like /app/:appname which should fetch template called /template/:appname.html. I know that the appname can be accessed from controller using :
$routeParams.appname;
But how can I render template based on that parameter ?
You could do this:
App.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/app/:appname', {
templateUrl : '/templates/app-template.html',
controller : 'AppCtrl',
resolve: {
appPath: function ($route) {
return $route.current.params.appname;
}
}
})
});
in AppCtrl,
App.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = [
'$scope'
'appPath'
];
function AppCtrl($scope, appPath) {
$scope.template = appPath + '.html';
}
in app-template.html, use ng-include as such
<div ng-include src="template"></div>
Hope this helps.
templateUrl can be use as function which returns a url.
App.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : '/templates/home.html',
controller : 'landing'
})
.when('/:appname',{
templateUrl: function(params){
return "templates/"+params.appname +".html"
},
controller: 'Ctrl'
});
});
Related
I am using http-server package to run my angular js project. My directory structure is below:-
angulardemo/app/public/controller
angulardemo/app/public/app.js
angulardemo/app/public/index.html
angulardemo/app/public/view
ang my app.js file is
var app = angular.module('angulardemo', ['ngRoute', 'ngCookies'])
.constant('API_URL', 'http://127.0.0.1:8001')
.config(function ($routeProvider, $locationProvider, $httpProvider) {
$httpProvider.defaults.headers.common = {'Content-Type' : 'application/json'};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
/**
*
* Checks for url access
*/
resolver = function (access){
return {
load: function($q, AuthService, $location){
if(access){
return true
}else{
if(AuthService.checkLogin()){
return true;
}
else{
$location.path("/login");
}
}
}
}
}
$routeProvider
.when('/', {
templateUrl : "/view/home.html",
controller : 'PagesController'
})
.when('/home', {
templateUrl : "/view/home.html",
controller : 'PagesController'
})
.when('/about', {
templateUrl : "/view/about.html",
controller : 'PagesController'
})
.when('/team', {
templateUrl : "/view/team.html",
controller : 'PagesController'
})
.when('/work', {
templateUrl : "/view/work.html",
controller : 'PagesController'
})
.when('/price', {
templateUrl : "/view/price.html",
controller : 'PagesController'
})
.when('/users/:user_type', {
templateUrl : "/view/developers.html",
controller : 'UsersController'
})
.when('/user/show/:id', {
templateUrl : "/view/user.details.html",
controller : 'UsersController'
})
.when('/contact', {
templateUrl : "/view/contact.html",
controller : 'PagesController'
})
.when('/register', {
controller: 'AuthController',
templateUrl: '/view/auth/register.html',
resolve:{
loggedIn: function(AuthService, $location){
if(!AuthService.checkLogin())
return true;
else
$location.path("/home");
}
}
})
.when('/login', {
controller: 'AuthController',
templateUrl: '/view/auth/login.html',
resolve:{
loggedIn: function(AuthService, $location){
if(!AuthService.checkLogin())
return true;
else
$location.path("/home");
}
}
})
.when('/dashboard', {
controller: 'DashboardController',
templateUrl: '/view/dashboard/index.html',
pageTitle: 'dashboard',
resolve:resolver(false)
})
.when('/users_personal/:id', {
controller: 'UsersController',
templateUrl: '/view/users/personal.html',
pageTitle: 'personal_details',
resolve:resolver(false)
})
.when('/users_edu/:id', {
controller: 'UsersController',
templateUrl: '/view/users/edu.html',
pageTitle: 'edu_details',
resolve:resolver(false)
})
.when('/users_contact/:id', {
controller: 'UsersController',
templateUrl: '/view/users/contact.html',
pageTitle: 'contact_details',
resolve:resolver(false)
})
.when('/users_other/:id', {
controller: 'UsersController',
templateUrl: '/view/users/other.html',
pageTitle: 'other',
resolve:resolver(false)
})
.when('/logout', {
resolve : {
logout: function ($routeParams, $location, $http, API_URL){
$http.get(API_URL + "/api/auth/logout").success(function (response) {
if(response === "OK"){
localStorage.removeItem('auth');
$location.path('/login').replace();
}
})
}
}
})
.otherwise({
redirectTo: '/',
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
}).hashPrefix('*');
}).run(['$http', '$cookies', function($http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
}]);
when I am running project using "http-server" with in the app directory command I got url as http://127.0.0.1:8080
http://192.168.10.137:8080
all the pages are working fine but when I am refreshing the page I am getting This 127.0.0.1 page can’t be found
No web page was found for the web address: http://127.0.0.1:8080/team
HTTP ERROR 404
So can anyone please tell that what wrong thing is here. and provide the solution.
See the directory structure in git hub:-
https://github.com/sanjaysamant/angulardemo/tree/local/app
Angular js files are in the public directory
Thanks
Please see terminal screen shot:
Whenever you are on a sub-URL such as /team and you refresh the page, the Node-Server looks for a HTML-File that is in the folder team on your server, which is not what you want. You need the server to redirect all those URL's to your index.html so that it loads the Angular Application, which can then properly initialize the correct page.
You can try the following in your server.js file:
//routes
app.use('/api/auth', require('./controllers/auth/auth.controller'));
app.use('/api/users', require('./controllers/users/users.controller'));
app.use('/api/user/', require('./controllers/users/users.controller'));
// Redirect unmatched routes (All specific routes such as /api/* need to be before this call)
app.use(redirectUnmatched);
function redirectUnmatched(req, res) {
res.redirect("/");
}
What #Chnoch suggested is correct, however I want to give you a different approach.
app.get('*', function(req, res)
{
res.send('/path/to/index.html');
});
Because all requests for a page will be a GET requests, you don't need to specify POST, and with this approach it will preserve the current URL you are on (eg. if you were on http://127.0.0.1:8080/team you will refresh and still be on /team), wheras #Chnoch's approach will always redirect you back to http://127.0.0.1:8080/.
What this will do is for any request that can't be resolved by the Node server, it will just render plain index page that can then be handled by Angular's ngRoute to display templates (you can also use templating engines like EJS or Pug with this, just replace the res.send with the rendering function).
Just make sure that the above code is after ALL other routes you want to be resolved by the Node server (eg. your API etc.) so it doesn't interfere with routes after it, since this is a catch all route.
I try to define stateParams in the controller, but it returns me an empty object {}
My app.js:
angular.module('testApp', ['ui.router','ngResource'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url:'/',
views: {
'header': {
templateUrl : 'views/header.html'
},
'messages': {
templateUrl : 'views/messages.html',
controller : 'MessageController'
},
'chat': {
templateUrl : 'views/chat.html',
controller : 'ChatController'
},
'footer': {
templateUrl : 'views/footer.html'
}
}
})
.state('app.chat', {
url: ':id'
});
$urlRouterProvider.otherwise('/');
})
My controller.js:
angular.module('testApp')
.controller('IndexController', ['$scope', '$stateParams', function($scope,$stateParams) {
$scope.chosenMessage = $stateParams;
}]);
And my template:
<div ui-view="messages" class="col-xs-6"></div>
<div ui-view="chat" class="col-xs-6"></div>
I need an id from StateParams to define choosen message and chat content for the message.
The solution:
I have defined $state instead of $stateParams, and check for $state.params.id to get current state.
This is how I am doing .Here is my code.
I need to have specific function for each route
var App = angular.module('App', ['ngRoute']);
App .config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'mainController'
})
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'mainController'
});
});
I guess you want to use the 'resolve' function. Try like below
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController',
resolve: {
val: function() {
// do whats needed here
return true;
}
})
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'mainController',
resolve: {
val: function() {
// do whats needed here
return true;
}
})
I'm using cordova angularjs together. I will use the routeprovider.
index.js:
var appGenerator = angular.module('appGenerator', ['ngRoute', 'ngResource']);
appGenerator.config(function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
});
appGenerator.config(['$routeProvider' function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "partials/tablePage.html",
controller: "MainCtrl"
})
.when('/contacts', {
templateUrl: "partials/contacts.html",
controller: "ContactsCtrl"
}).otherwise({
redirectTo: '/'
}); }]);
html:
{{table.tablename}}
But I get an net::ERR_FILE_NOT_FOUND(file:///contacts) error
What I'm doing wrong?
I'm building an App that requires authentication and I need to check if the user is authenticated when changing routes before instantiating the route Controller, so I need a function to retrieve the logged user from the server with $http that I need to call in the resolve property of the 'when' and then pass the retrieved user to the controller. How can I declare the function?
This is my app.js
angular.module('MasterToolsApp', ['ui.bootstrap', 'ngRoute', 'ngSanitize', 'ngResource', 'ngAnimate', 'dialogs.main', 'toasty']);
angular.module('MasterToolsApp')
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/login'
})
.when('/login', {
templateUrl : 'dist/templates/login.html',
controller : 'LoginController',
resolve : ?
})
.when('/home', {
templateUrl : 'dist/templates/home.html',
controller : 'HomeController',
resolve : ?
})
.when('/entries', {
templateUrl : 'dist/templates/entries.html',
controller : 'EntriesController',
resolve : ?
})
.otherwise({ redirectTo: '/login' });
}]);
I found the answer in another question: Related Question
The resulting code is this:
angular.module('MasterToolsApp', ['ui.bootstrap', 'ngRoute', 'ngSanitize', 'ngResource', 'ngAnimate', 'dialogs.main', 'toasty']);
var Helpers = {
checkAuthentication: function($http) {
return $http(
{
url : '/auth',
method : 'GET',
headers : {'Content-Type': 'application/x-www-form-urlencoded'},
timeout : 10000
}
);
}
};
angular.module('MasterToolsApp')
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/login'
})
.when('/login', {
templateUrl : 'dist/templates/login.html',
controller : 'LoginController',
resolve : {
user: ['$http', function($http) {
return Helpers.checkAuthentication($http);
}
]
}
})
.when('/home', {
templateUrl : 'dist/templates/home.html',
controller : 'HomeController',
resolve : {
user: ['$http', function($http) {
return Helpers.checkAuthentication($http);
}
]
}
})
.when('/entries', {
templateUrl : 'dist/templates/entries.html',
controller : 'EntriesController',
resolve : {
user: ['$http', function($http) {
return Helpers.checkAuthentication($http);
}
]
}
})
.otherwise({ redirectTo: '/login' });
}]);