I would like to have two main pages (logged in, logged out), which have url like '/'.
Is it posiible to do it with ngRoute?
I was searching the soltion but everywhere was to use ui-router.
Now I have sth like:
$rootScope.$on('$routeChangeStart', function (event, next) {
if ( next.$$route.orginalPath == '/' && loggedIn ) {
next.$$route.templateUrl = "app/main/main-loggedIn.html"
} else {
next.$$route.templateUrl = "app/main/main-loggedOut.html"
}
});
and
angular.module('name').config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/main/main-loggedOut.html',
controller: 'MainCtrl'
})
});
but it doesn't work well. It changes the templateURL but it get data before that changings and load always loggedOut page.
I have also the solution to put both html in one file in set them ng-if, but I prefer to avoid it.
solution:
main.html
<div ng-include="mainTemplate"></div>
main.js
angular.module('bookkeepingApp').config(function ($routeProvider) {
$routeProvider.when('/', { controller: 'MainCtrl', templateUrl: "app/main/main.html" })
}).controller('MainCtrl', function ($scope, Auth) {
$scope.$watch(function($scope) {
return $scope.mainTemplate = Auth.isLoggedIn() ? 'app/main/main-loggedIn.html' : 'app/main/main-loggedOut.html';
})
});
I don't know how you're getting the loggedIn value, but templateUrl accepts a function as value, you just have to return the correct one, based on the information of the user. I guess the code above might work.
angular.module('name').config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: function() {
return loggedIn ? "app/main/main-loggedIn.html" : "app/main/main-loggedOut.html"
}
})
});
You can put a template within a template, i.e in your route "/" you have a
<div ng-include="scopeVariable">
</div>
the scope variable points to a loggedin/loggedout page depending on your needs.
Related
Is it possible to use Angularjs's routing and controller without the templateURL?
For instance, below is my current routes, controllers, and template urls,
return app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/",
{
templateUrl: "js/template/1.html",
controller: "controller1"
})
.when("/list1",
{
templateUrl: "js/template/2.html",
controller: "controller2"
})
...
And I have ng-view in my html,
<div ng-view></div>
I tested with the routes without templateUrl,
return app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/",
{
//templateUrl: "js/template/1.html",
controller: "controller1"
})
.when("/view1",
{
//templateUrl: "js/template/2.html",
controller: "controller2"
})
...
the result - nothing is displayed on my screen. obviously the controller cannot be triggered anymore.
use template with empty string.
return app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/",
{
template: "",
controller: "controller1"
})
Angular uses the $routeProvider Definition to attach a controller to your view. If you don't want to specify the details in $routeProvider config, other option is to let the application land on one page using something like -
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html'
})
.when()
.otherwise({
redirectTo: '/'
});
});
This way user will land on main.html. Now on the main.html you can include several different html templates like -
<div ng-include src="'js/template/1.html'" ng-controller = 'Controller1'></div>
<div ng-include src="'js/template/2.html'" ng-controller = 'Controller2'></div>
Notice the syntax of using/including template above - "'<<Path>>'"
Hope this helps.
Setting template with empty string make error and cause recursion loading ; i solved it by just add the link of empty html file.
return app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/",
{
template: "dummy.htm",
controller: "controller1"
})
When the page loads, the alert fires twice. I am expecting it to fire only once.
This is causing duplicate data insertion in an array inside init function.
Why is this happening. Is it something to do with the routing definitions. How to stop it.
indexctrl.js:
app.controller("indexctrl", function ($scope, $routeParams) {
var uPId = $routeParams.pqid;
var uCId = $routeParams.cid;
if (uPId != null && uCId != null) {
//some other code
}
else {
alert('test');
init();
}
var init = function(){
//some code
}
}
app.js:
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'App/views/index.html',
controller: 'indexctrl'
})
.when('/Index', {
templateUrl: 'App/views/index.html',
controller: 'indexctrl'
})
.when('/Index/pqid/:pqid/cid/:cid', {
templateUrl: 'App/views/index.html',
controller: 'indexctrl'
})
.otherwise({
redirectTo: '/'
});
}]);
1. Check your controller is declared in html file as well.
2.The link which is referring to routes should be like this <a href="#/Index">
3.If your working with another frame works like ionic. it has aleardy angular.js file.so check how many time your loading script file.
I just started with angularJS and I have a question:
How can I access a variable defined with $rootScope in a templateUrl function?
Here is my code:
myApp.config(['$routeProvider',
function($routeProvider, $rootScope) {
$routeProvider.
when( '/', {
templateUrl: 'partials/login.html',
controller: 'loginCtrl'
}).
when( '/home', {
templateUrl: function($rootScope){
console.log($rootScope.utilisateur.user.role_id);
if ($rootScope.utilisateur.user.role_id==2){
return 'partials/home.html';
}
else return 'partials/login.html';
},
controller: 'homeCtrl'
}).
otherwise({redirectTo:'/'});
}]);
It tells me that utilisateur is undefined.
I defined it in the index controller:
$rootScope.utilisateur = null;
$rootScope.rapports = null;
And then in the LoginCtrl:
var user = Authentification.login(email,password);
user.success(function(response){
$rootScope.utilisateur = response;
console.log($rootScope.utilisateur);
$location.path('/home');
});
You cannot use the $rootScope inside of the config block, as the config block runs before the $rootScope is created. Constants and providers may be used inside of the config block instead. If constants are not an option for you, you may want to redirect to the correct url inside of your homeCtrl.
[EDIT] Added possible solution from comment below:
Option 1: Have 2 different routes
/admin/home
/home
Option 2: Switch templates according to permission inside of controller/view
home.html
<div ng-switch="utilisateur.user.role_id">
<div ng-switch-when="2">
<!-- is admin -->
</div>
<div ng-switch-default>
<!-- not admin -->
</div>
</div>
Not the ideal solution, but it'd work for what you are trying to do, based on your comments below
Your problem seems like you have two different views, and on condition base you have to redirect views.
Pass the parameters in url like from your views (Create/Edit link etc.) As i have set the cookie on login and accessed here as a parameters or you can use different way to access the parameters.
''
And your config in $routeProvider use like this:
$routeProvider.when("/editTest/:ID/:flagTab",
{
templateUrl: function (params) {
var flag = params.flagTab;
if (flag == 'tabPanelView') {
return '/apps/templates/editTest.html';
}
else {
return '/apps/templates/editTestPageView.html';
}
},
controller: 'EditTestController'
});.
Refere a link swtiching views in routeProvider based on condition
Instead of describing different ways to achieve what you would like to, the code snippet below answers the actual question that was asked:
How can I access a variable defined with $rootScope in a templateUrl function?
The answers above and here imply there is no way to reference $rootScope within the config/$routeProvider. While that may strictly be true, there is a simple way to access the $rootScope through $routeProvider. Below is how to do this:
Sample HTML:
<div ng-app="myApp">
<div ng-controller="masterController">
<script type="text/ng-template" id="home.html">{{something}}</script>
Page
<div ng-view></div>
</div>
</div>
Sample javascript:
var myApp = angular.module('myApp',[],function($routeProvider) {
$routeProvider
.when('/home',{templateUrl:'home.html'})
.when('/page',
{
template:'<p>{{something}}</p>',
controller:'masterCtrlWrapper'
})
.otherwise({redirectTo:'/home'});
});
myApp.controller('masterCtrlWrapper', function($rootScope)
{ $rootScope.changeVariable(); });
myApp.controller('masterController', function($rootScope)
{
$rootScope.something = 'This is the $rootScope talking.'
$rootScope.pressCount = 0;
$rootScope.changeVariable = function()
{ $rootScope.something = "This function was run " + $rootScope.pressCount++ + " times."; };
});
Like others have said, $rootScope doesn't exist yet, but unlike their answers, it doesn't at all mean you can't use it at all, you just have to code-in the wait.
Here is your example working but just printing since we dont have the templates.
myApp
.provide('home', function() {
var $rootScope = null;
this.templateUrl = function() {
var check =
$rootScope.utilisateur &&
$rootScope.utilisateur.user.role_id
;
console.log(check);
return (check) ? 'partials/home.html' : 'partials/login.html';
};
this.controller = 'homeCtrl';
this.resolve = {load:['$rootScope', function(fetched) { $rootScope = fetched; }]};
this.$get = function() { };
})
.config(['$routeProvider', 'homeProvider', function($routeProvider, homeProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/login.html',
controller : 'loginCtrl'
})
.when('/home', homeProvider)
.otherwise({redirectTo:'/'})
;
}])
;
I am an amateur with angular. I am using route provider to load separate html pages and controllers. This works fine when I know what pages the site has and I can define them.
app.config(function($routeProvider) {
$routeProvider
.when("/page1", {
templateUrl: "../page1.html",
controller: "Page1Ctrl"
})
.when("/page2", {
templateUrl: "../page2.html",
controller: "Page2Ctrl"
})
.when("/page3", {
templateUrl: "../page3.html",
controller: "Page3Ctrl"
})
.otherwise({
redirectTo: "/page1"
});
});
However, in future, more pages may be added and I want to code a way for angular to take this into accout. Something like;
app.config(function($routeProvider) {
(..figure out n...)
$routeProvider
.when("/page"+n, {
templateUrl: "../page"+n+".html",
controller: "Page"+n+"Ctrl"
})
.otherwise({
redirectTo: "/page1"
});
});
I cannot figure out how to return a var listing the current page so I can remove '/page' to manipulate the int as n.
I tried console logging $routeProvider but .when simply returns a function. I don't think injecting $scope is wise because obviously a var is passed somewhere using $routeProvider alone.
If you use colon (:) in the route, Angular will parse that and populate the $routeParams with it, then, in your templateUrl, instead of a string, you can use a function which returns the template url. Just inject the $routeParams in the templateUrl's function and build the url you need.
$routeProvider
.when( '/page/:pageNumber', {
templateUrl: function ($routeParams) {
return 'page_' + $routeParams.pageNumber + '.html'
}
})
.otherwise( { redirectTo: '/page/1' } );
Here is a working fiddle.
I have the following bit of code for my navigation that I want to update dynamically between pages.
<nav ng-include="menuPath"></nav>
Here is my app and routing set up
var rxApp = angular.module('ehrxApp', ['ngRoute']);
// configure our routes
rxApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'mainController',
templateUrl: '/content/views/index.html'
})
.when('/census', {
templateUrl: '/content/views/admission/census.html',
controller: 'censusController'
})
.when('/messages', {
templateUrl: '/content/views/account/messages.html',
controller: 'messagesController'
})
.when('/profile', {
templateUrl: '/content/views/account/profile.html',
controller: 'profileController'
})
});
In my main controller I set the menuPath value here:
rxApp.controller('mainController', function (userService, $scope, $http) {
evaluate_size();
$scope.menuPath = "/content/views/index.menu.html";
});
rxApp.controller('censusController', function ($scope, $http, $sce, censusService) {
$scope.menuPath = "/content/views/admission/census.menu.html";
evaluate_size();
});
When the page switches to the census view it should change the menu. What happens though is the first page loads the main menu, then no matter what other page you go to the menu never updates.
I imagine this problem has something to do with a primitive values and prototypical inheritance between child scopes, but would need to see more of your html to determine that. Without that, I propose an alternative way that may solve your problem and keep the config all in one place.
$routeProvider will accept variables and keep them on the route, even if angular doesn't use them. so we modify your routing by including the menuPath like so:
var rxApp = angular.module('ehrxApp', ['ngRoute']);
// configure our routes
rxApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'mainController',
templateUrl: '/content/views/index.html',
menuPath: '/content/views/index.menu.html'
})
.when('/census', {
templateUrl: '/content/views/admission/census.html',
controller: 'censusController',
menuPath: '/content/views/admission/census.menu.html'
})
.when('/messages', {
templateUrl: '/content/views/account/messages.html',
controller: 'messagesController'
})
.when('/profile', {
templateUrl: '/content/views/account/profile.html',
controller: 'profileController'
})
});
Remove setting $scope.menuPath from each controller, then finally add a watch on rootScope that will change the menuPath on $routeChangeSuccess
rxApp.run(['$rootScope', function ($rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current) {
if (current && current.$$route && current.$$route.menuPath) {
$rootScope.menuPath = current.$$route.menuPath;
} else {
$rootScope.menuPath = '';
}
});
}]);