How can i add another one route in this code? - javascript

i need to add admin user. I read that i need to separate routes in my app.js file. But i can't find example that i need to done this. May be someone can help me to fix this problem ?
(function () {
'use strict';
angular
.module('app', ['ngRoute', 'ngCookies'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'login/login.view.html',
controllerAs: 'vm'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'register/register.view.html',
controllerAs: 'vm'
})
.when('/admin', {
controller: 'AdminController',
templateUrl: 'admin/admin.view.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/login' });
}
run.$inject = ['$rootScope', '$location', '$cookies', '$http'];
function run($rootScope, $location, $cookies, $http) {
// 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) {
// redirect to login page if not logged in and trying to access a restricted page
var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
})();

Take a look at this gist
Basically what you need is attach some restriction related data to your route and check on page transition if you are authorized and redirect if not.
Dedicated AuthService can contain currentUser and authorization data instead of chaotic data in the run block.

Related

Error: [$compile:tpload] in iOS

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.

Multiple url changes with $routeChangeStart

Hi all I having a hard time figuring this out and ran out of ideas. I have this website which I should restrict some urls if the user has no authentication. I reviewed some questions and found something similar to this. But it is not quite what I wanted it to be.
So I have some link which do not require user authentication but can access the url.
Other link which needs both, access and user authentication.
So this is my app.js looks
angular.module('efutures', [
'ngRoute',
'ngCookies',
'ui.bootstrap',
]).config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
$routeProvider.when('/login', {
templateUrl: 'app/pages/login.html',
controller: 'LoginController',
access: {
allowAnonymous: true //no need auth
}
})
.when('/signup', {
templateUrl: 'app/pages/Signup.html',
controller: 'SignupController',
access: {
allowAnonymous: true //no need auth
}
})
.when('/enteremail', {
templateUrl: 'app/pages/reset pages/reenteremail.html',
controller: 'EmailController',
access: {
allowAnonymous: true //no need auth
}
})
.when('/password-reset', {
templateUrl: 'app/pages/reset pages/password.reset.html',
controller: 'ResetPwdController',
access: {
allowAnonymous: false //needs auth
}
})
.when('/dashboard', {
templateUrl: 'app/pages/dashboard.html',
controller: 'DashboardController',
access: {
allowAnonymous: false //needs auth
}
})
.when('/registration', {
templateUrl: 'app/pages/registration1.html',
controller: 'registationController'
access: {
allowAnonymous: false //needs auth
}
});
$routeProvider.otherwise({
redirectTo: '/login'
});
}]).run(run);
run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
function run($rootScope, $location, $cookieStore, $http) {
$rootScope.hasauth = localStorage.getItem('hasauth');
$rootScope.username = localStorage.getItem('username');
$rootScope.$on('$routeChangeStart', function (event, next, current) {
//console.log($rootScope.hasauth);
//console.log(next.access.allowAnonymous);
if (next.access.allowAnonymous || $rootScope.hasauth === null) {
$location.path('/login');
}
else {
event.preventDefault();
}
});
}
So as above explains code, I have 3 pages which doesn't need authentication and can be allowed to access the urls. Also after Logged in I should restrict going back to those 3 pages but should access other remaining ones
the authentication is taken by the loacalStorage hasauth which returns true when logged in and null when not.
How do I approach this? Help is greatly appreciated.

Angular ng-view not displaying [leaning angular]

I'm learning Angular and I'm having problem on the routing. I've tried to solve it myself but have no idea what it can be.
Here's my script and a Plunker link of my script
var singleApp = angular.module('singleApp', ['ngRoute'])
.config([$routeProvider, $locationProvider, function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
.when('/contact', {
templateUrl: 'pages/contact.html',
controller: 'contactController'
});
// Deletes # in URL with HTML History API
$locationProvider.html5Mode(true);
}])
.controller('mainController', function($scope) {
$scope.message = 'This is the main page';
})
.controller('aboutController', function($scope) {
$scope.message = 'This is the about page';
})
.controller('contactController', function($scope) {
$scope.message = 'This is the message page';
});
I've imported the both angular and routing scripts in html.
The pages has just $message
The first issue is with your config. You're using a great practice by using an array for your injections but the first arguments must be strings. Change this:
.config([$routeProvider, $locationProvider, function($routeProvider, $locationProvider) {
to this
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
Then... remove this line:
$locationProvider.html5Mode(true);
Here's information about HTML5 mode:
https://docs.angularjs.org/error/$location/nobase
Enabling HTML 5 Mode in AngularJS 1.2
http://plnkr.co/edit/EXMiz3bAEttTQac0uvgh?p=preview
You have syntax error, config function should be like this
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
http://plnkr.co/edit/4csvt10yfolOepqECh51?p=preview
Removes the following line
//Deletes # in URL with HTML History API
$locationProvider.html5Mode(true);
Many of the errors and especially reference can view them in the browser console
You must modify the parameters of your config, should go well
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
Compare and see your code
var singleApp = angular.module('singleApp', ['ngRoute'])
singleApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
.when('/contact', {
templateUrl: 'pages/contact.html',
controller: 'contactController'
});
});
singleApp.controller('mainController', function($scope) {
$scope.message = 'This is the main page';
});
singleApp.controller('aboutController', function($scope) {
$scope.message = 'This is the about page';
});
singleApp.controller('contactController', function($scope) {
$scope.message = 'This is the message page';
});

Angular: Passing params from $routeProvider to controller

I have multiple routes that invoke the same Controller and I would like to pass different variables to it.
// Example
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed 'exampleA'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed 'exampleB'
});
I know that I could use the "resolve" object:
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController',
resolve: {test: function() { return true; }}
});
To pass a value as a dependency:
app.controller('MyController', ['$scope', 'test', function ($scope, test) {
console.log(test); // true
}
My problem with that approach is that my app crashes if the resolve object is missing on other routes and I would like to pass optional params.
Is there any way to pass specific params to the Controller (from the route provider)?
Thank you
Routing:
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController',
paramExample: 'exampleA'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController',
paramExample: 'exampleB'
});
Access: inject $route in your controller then use this
app.controller('MyController', ['$scope', '$route', function ($scope, $route) {
var paramValue = $route.current.$$route.paramExample;
console.log(paramValue);
}
You can use resolve and $route.currrent.params.test to pass the parameter like this:
$routeProvider
.when('/a', {
templateUrl: 'view.html',
controller: 'MainCtrl',
resolve: {
test: function ($route) { $route.current.params.test = true; }
}
})
.when('/b', {
templateUrl: 'view.html',
controller: 'MainCtrl',
resolve: {
test: function ($route) { $route.current.params.test = false; }
}
})
Then in your controller you can access it from the $routeParams:
app.controller('MainCtrl', function($scope, $routeParams) {
$scope.test = $routeParams.test;
})
http://plnkr.co/edit/ct1ZUI9DNqSZ7S9OZJdO?p=preview
The most natural way to do this is doing what you would normally do when you want to load a page with parameters: use query parameters: http://yoururl.com?param1=value&param2=value
ngRoute comes with the service $routeParams which you can inject in your controller. Now you can simply retrieve the values like this $routeParams.param1.
Another way to do this is to retrieve the path with $location.path and set the variable there.
using $routeParams
in Main js file
routeApp.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: '../sites/./home.html',
controller: 'StudentController'
})
.when('/viewStudents/:param1/:param2', {
templateUrl: '../sites/./viewStudents.html',
controller: 'StudentController'
})
.otherwise({
redirectTo: '/'
});
});
routeApp.controller('StudentController',['$filter','$routeParams', '$location',function($filter,$routeParams,$location){
var StudentCtrl = this;
StudentCtrl.param1 = $routeParams.param1;
StudentCtrl.param2 = $routeParams.param2;
}]);
calling from Home.html
<div class="container">
<h2> Welcome </h2>
Students
</div>

AngularJS, $routeProvider

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

Categories