I want pass the value to one nerds controller to geek controller but unable to pass in ng-router.
<button type="Submit" ng-click="showUser()">Show Details</button>
.when('/geeks', {
templateUrl: 'views/geek.html',
controller: 'GeekController'
})
.when('/nerds', {
templateUrl: 'views/nerd.html',
controller: 'NerdController'
})
In Nerds controller I have this function
$scope.showUser=function(){
$rootScope.$broadcast('btnName',{message:"msg"})
}
In geek controller I receiving the value on page load itself but i am not getting the value pls help me to find the solution
$rootScope.$on('btnName',function(event,args){
$scope.msg=args.message;
console.log("$scope.message nnnn",$scope.msg)
})
The NerdController and the GeekController are in two separate pages, only one of the controllers can be active at a time, since angular has only one page open in the tab. So what I suggest is, pass the variable as a parameter to the route, you can see this in the example below.
JSFiddle Demo
JS:
var routingExample = angular.module('Example.Routing', []);
routingExample.controller('NerdController', function ($scope, $location) {
$scope.showUser = function(){
console.log("show");
$location.path('/geek/1');
}
});
routingExample.controller('GeekController', function ($scope, $routeParams) {
$scope.id = $routeParams.id;
});
routingExample.config(function ($routeProvider) {
$routeProvider.
when('/nerds', {
templateUrl: 'home.html',
controller: 'NerdController'
}).
when('/geek/:id', {
templateUrl: 'blog.html',
controller: 'GeekController'
}).
otherwise({
redirectTo: '/nerds'
});
});
Related
I have url like this:
http://localhost:3000/details/59567bc1de7ddb2d5feff262
and I want to get the parameter id
59567bc1de7ddb2d5feff262
But for some reasons routeParam always returns undefined
My controller is:
task.controller('ctrla', function($rootScope, $scope, $http, $timeout, $routeParams){
$scope.first = 1;
console.log($routeParams);
});
routes :
task.config(function ($routeProvider, $locationProvider){
$routeProvider.when('/details/:id', {
templateUrl: "details.html",
controller: "ctrla"
})
});
any help will be a life save.
Make sure you have defined the route urls as mentioned below,
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
template: "HI this is home Screen",
controller: 'ctrla'
})
.when('/details/:id', {
templateUrl: "template.html",
controller: 'profileController'
})
.otherwise({
redirectTo: '/home'
})
}]);
DEMO
If yu have route deinition defined as
$routeProvider.when('/details/:id', {
templateUrl: "partial.html",
controller: "ctrla"
})
Then in controller you should get its value as
task.controller('ctrla', function($rootScope, $scope, $http, $timeout, $routeParams){
$scope.first = 1;
console.log($routeParams.id);
});
I have the following routing:
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/panel', {
templateUrl: 'views/panel.html'
}).
when('/make', {
templateUrl: 'views/makePanel.html',
controller: 'painelCtrl'
}).
when('/paneluser', {
templateUrl: 'views/panelUser.html',
controller: 'userCtrl'
}).
when('/paneluserblocks', {
templateUrl: 'views/userPanels.html',
controller: 'userCtrl'
}).
when('/registred', {
templateUrl: 'views/registredPanels.html'
}).
when('/color', {
templateUrl: 'views/color.html',
controller: 'alarmCtrl'
}).
otherwise('/', {
templateUrl: 'Index.html',
});
}]);
When I specify a controller for a particular html template, my $scope variables are no longer updated in the view.
When I pull out the controller specification for a particular route, things return to normal.
The controller 'userCtrl' is accessed through $location and is intended for ordinary users. In turn, 'Ctrl panel' is the primary controller assigned to admin users.
Could anyone tell me what's going on?
I haven't all information, but it's working in my demo.
Config
var app = angular.module('app',['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/panel', {
templateUrl: 'views/panel.html'
}).
when('/make', {
templateUrl: 'views/makePanel.html',
controller: 'painelCtrl'
}).
otherwise('/', {
templateUrl: 'Index.html',
});
}]);
Definition of your controller:
app.controller('painelCtrl',painelCtrl);
painelCtrl.$inject = ['$scope'] //and more if you need $http, services, ...
function painelCtrl($scope){
$scope.hello= "hello world"
}
HTML
<h1>{{hello}}</h1>
I'm sorry for the igenuidade. I believed that the pages being in the same controller, I would never miss the reference:
When ('/panel', {
TemplateUrl: 'views/panel.html',
Controller: 'panelCtrl'
}).
When ('/make', {
TemplateUrl: 'views/makePanel.html',
Controller: 'panelCtrl'
}). cotinue...
In fact, views panel.html and makePanel.html will use the same controller structure, however we will have one instance for each view (variables will be reseted).
In my case I used factory functions to solve the problem. Every time I mute controller, I store the information of interest through a set () and get it through a get ();
app.factory("MonitorService", function () {
var info;
function set(data) {
info = data;
}
function get() {
return info;
}
return {
set: set,
get: get
}
});
I am trying to have two different templates. One that is the landing page for logged out users describing about the business and the other dashboard page for if a user is logged in.
I read on this other stack on how to do this with UI-router. I would like to know the best practice to do something similar like this using ngRoute?
The way it is setup below, is that "/frontdesk" is the dashboard and "/" is the landing page for logged out users. BUT! I want the URL to be the same for whether the user is on the dashboard or is logged out and sent to the landing page! I do not want "/frontdesk", I want "/" for IndexController and FrontdeskController.
Here is my routing JS.
(function () {
'use strict';
angular
.module('resonanceinn.routes')
.config(config);
config.$inject = ['$routeProvider'];
function config($routeProvider) {
$routeProvider
.when('/', { // This is the landing Page
controller: 'IndexController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/layout/index.html'
})
.when('/frontdesk', { //This is logged in user that I want to become '/' as well
controller: 'FrontdeskController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/frontdesk/frontdesk.html'
})
.when('/register', {
controller: 'RegisterController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/authentication/register.html'
})
.when('/login', {
controller: 'LoginController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/authentication/login.html '
})
.when('/:username', {
controller: 'ProfileController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/profiles/profile.html'
})
.when('/:username/settings', {
controller: 'ProfileSettingsController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/profiles/settings.html'
}).otherwise('/');
}
})();
Solution!
Thank you everyone for your answers.
Thanks to #ThibaudL for the better solution.
This is how I ended up doing it:
In Routes.js
.when('/', {
controller: 'MainController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/layout/Main.html'
Main.html
<div ng-include="" src="'/static/javascripts/layout/index.html'" ng-if="auth"></div>
<div ng-include="" src="'/static/javascripts/frontdesk/frontdesk.html'" ng-if="!auth"></div>
MainController.js
(function () {
'use strict';
angular
.module('resonanceinn.layout.controllers')
.controller('StartController', StartController);
StartController.$inject = ['$scope', '$route', '$routeParams', '$location', 'Authentication'];
function StartController($scope, $route, $routeParams, $location, Authentication) {
$scope.auth = Authentication.isAuthenticated();
}
})();
So now if the user is Authenticated, it just switches the templates to the users dashboard.
I added a new div with ng-controller to each template so that each template has their separate controllers.
Add another property, like this isGuest: true
.when('/', {
controller: 'IndexController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/layout/index.html',
isGuest: true
})
.... ...............
and
app.run(function($rootScope, $state, Session) {
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
if (toState.isGuest == true && Session.isAuthenticated()) {
// User isn’t authenticated
// do redirection to guest user
event.preventDefault();
}
if (toState.authentication == true && !Session.isAuthenticated()) {
// do redirection to loggedin user
event.preventDefault();
}
});
});
You can write your own service Session,
Session.isAuthenticated() // returns true or false,based on whether user is guest or loggedin
You can use resolve property to check if user is logged in.
$routeProvider
.when('/somepage' ,{
templateUrl: "templates/template.html",
resolve:{
"check":function($location){
if('Your Condition'){
//Do something
}else{
$location.path('/'); //redirect user to home.
alert("You don't have access here");
}
}
}
})
Inject $locationProvider with your $routeProvider
config.$inject = ['$locationProvider'];
then
function config($routeProvider, $locationProvider ) {
$routeProvider
.when('/', {
controller: 'IndexController',
controllerAs: 'vm',
template: " "
})
...
note its template not templateUrl, also the template is " " note just ""
then in your index controller
.controller('IndexController', function($scope, $route, $routeParams, $location) {
if ($scope.user.loggedIn) $location.path('/:user'); else $location.path('/:visitor');})
note that same path as '/' but /:user for loggedIn users and /:visitor for anonymous
What I would do is :
Main.html
<div ng-include="" src="'/static/javascripts/layout/index.html'" ng-if="auth"></div>
MainController.js
(function () {
'use strict';
angular
.module('App.layout.controllers')
.controller('MainController', MainController);
MainController.$inject = ['$scope', '$route', '$routeParams', '$location', 'Authentication'];
function MainController($scope, $route, $routeParams, $location, Authentication) {
$scope.auth = Authentication;
});
}
})();
there are a couple of things you can do, the simplest being, checking for a logged in status in the beginning of your FrontdeskController and navigate to the homepage if not logged in.
you can also add variables on the route and check for them like in the previous answer.
there are more extreme cases you can do, which I find to be very bad practice, like writing a double state template page, but again, that's not a good thing to do.
I hope this helped
For templateUrl, you can use a function like,
templateUrl : function(parameter) {
if(loggedin) {
return '/static/javascripts/layout/index.html';
} else {
return 'logged out page';
}
}
You can read $routeProvider,
templateUrl – {string=|function()=} – path or function that returns a path to an html template that should be used by ngView.
If templateUrl is a function, it will be called with the following parameters:
{Array.< Object >} - route parameters extracted from the current $location.path() by applying the current route
Here's a complete solution:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'IndexController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/layout/index.html'
})
.when('/frontdesk', {
controller: 'FrontdeskController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/frontdesk/frontdesk.html',
requireLogin: true
});
});
app.factory('authService', function () {
var service = {
isAuthenticated: false,
loginPageUrl: '/login'
};
return service;
});
app.run(function ($rootScope, $location, authService) {
$rootScope.$on('$routeChangeStart', function (event, next) {
if (angular.isDefined(next) && next !== null && angular.isDefined(next.requireLogin)) {
if (next.requireLogin === true && !authService.isAuthenticated) {
event.preventDefault();
$location.path(authService.loginPageUrl);
}
}
});
});
First Attempt
.
In Routes.js
.when('/', {
controller: 'MainController',
controllerAs: 'vm',
templateUrl: '/static/javascripts/layout/Main.html'
Main.html
<div ng-include="mainTemplate"></div>
MainController.js
(function () {
'use strict';
angular
.module('App.layout.controllers')
.controller('MainController', MainController);
MainController.$inject = ['$scope', '$route', '$routeParams', '$location', 'Authentication'];
function MainController($scope, $route, $routeParams, $location, Authentication) {
$scope.$watch(function($scope) {
return $scope.mainTemplate = Authentication.isAuthenticated() ? '/static/javascripts/layout/index.html' : '/static/javascripts/frontdesk/frontdesk.html';
});
}
})();
So now if the user is Authenticated, it just switches the templates to the users dashboard.
I added a new div with ng-controller to each template so that each template has their separate controllers.
There are 2 views with respective controllers.
The links are in View1.Clicking on this link should load View2 and also read the parameters.
This is what I have tried but the alert says - undefined.
View2 can load with/without params - each case having a different workflow.
View1.html:
<div ng-controller="view1ctrl">
<a href="#/view2/pqid/775/cid/4" >Link1</a>
</div>
app.js:
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'App/views/view1.html',
controller: 'view1ctrl'
})
.when('/view2', {
templateUrl: 'App/views/view2.html',
controller: 'view2ctrl'
})
.when('/view2/:pqid/:cid', {
templateUrl: 'App/views/view2.html',
controller: 'view2ctrl'
})
.otherwise({
redirectTo: '/view1'
});
}]);
view2ctrl.js:
app.controller("view2ctrl", ['$scope','$routeParams',function ($scope, $routeParams) {
var init = function () {
alert($routeParams.pqid);
}
init();
}]);
You are nearly there:
.when('/view2/:pqid/:cid'
maps to a URL in this format :
view2/1234/4567
1234 being the pqid and 4567 the cid.
So your routing, I think is working, just change the link to #/view2/775/4.
Or if you want to keep the same link change your routing to:
#/view2/pqid/:pqid/cid/:cid
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 = '';
}
});
}]);